Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
387 views
in Technique[技术] by (71.8m points)

r - 从数据框中提取特定列(Extracting specific columns from a data frame)

I have an R data frame with 6 columns, and I want to create a new dataframe that only has three of the columns.

(我有一个包含6列的R数据框,并且我想创建一个仅包含三列的新数据框。)

Assuming my data frame is df , and I want to extract columns A , B , and E , this is the only command I can figure out:

(假设我的数据帧是df ,并且我想提取列ABE ,这是我唯一能知道的命令:)

 data.frame(df$A,df$B,df$E)

Is there a more compact way of doing this?

(有没有更紧凑的方法可以做到这一点?)

  ask by Aren Cambre translate from so

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

You can subset using a vector of column names.

(您可以使用列名称的向量作为子集。)

I strongly prefer this approach over those that treat column names as if they are object names (eg subset() ), especially when programming in functions, packages, or applications.

(与将列名视为对象名(例如, subset() )对待的方法相比,我特别喜欢这种方法,尤其是在函数,程序包或应用程序中进行编程时。)

# data for reproducible example
# (and to avoid confusion from trying to subset `stats::df`)
df <- setNames(data.frame(as.list(1:5)), LETTERS[1:5])
# subset
df[,c("A","B","E")]

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...