让我说我有两个不同的df's
:details
和df
详细
header <- c("header1","header6","header3","header4","header5")
type <- c("type1","type2","type3","type4","type5")
details <- data.frame(header, type)
details
header type
1 Header1 Type1
2 Header6 Type2
3 Header3 Type3
4 Header4 Type4
5 Header5 Type5
DF
x <- c("test","test","test")
header1 <- x
header2 <- x
header3 <- x
df <- data.frame(header1,header2,header3)
df
header1 header2 header3
1 test test test
2 test test test
3 test test test
现在我想和他们一起保留两者中的内容,所以它会像这样:
header1 header3
1 test test
2 test test
3 test test
我试图这样做:
df <- df[details$header]
但它显示了以下错误消息:
Error in `[.data.frame`(df, details$header) : undefined columns selected
如何创建新的df,只保留details$header
中存在的列?
答案 0 :(得分:0)
错误主要是由于标题中的元素所致。列的详细信息&#39;这不是列名。要使其有效,请使用intersect
df[intersect(names(df), as.character(details$header))]
# header1 header3
#1 test test
#2 test test
#3 test test
答案 1 :(得分:0)
df[names(df)%in%details[,1]]# df[names(df)%in%details$header]
header1 header3
1 test test
2 test test
3 test test