子集数据框用R中的NA填充某些列

时间:2014-06-16 16:35:32

标签: r dataframe subset

我想对数据进行子集化,并使用NA值填充某些列中的所有行。通过示例更容易理解:

x[,c(1,3,NA,5,NA)]

返回:

enter image description here

我知道这显然不会起作用,因为我在x中没有这些NA列。但有没有办法做到这一点?或许将两个子集与NA列粘贴在一起?

1 个答案:

答案 0 :(得分:0)

根据@konvas的建议,只需使用cbind

这是一个有效的例子:

mydf <- data.frame(trait1 = 1:2, something = c("A", "B"), 
                   trait2 = 3:4, nothing = c("C", "D"), height = 5:6)
mydf
#   trait1 something trait2 nothing height
# 1      1         A      3       C      5
# 2      2         B      4       D      6
cbind(mydf[c(1, 3)], NA, mydf[5], NA)
#   trait1 trait2 NA height NA
# 1      1      3 NA      5 NA
# 2      2      4 NA      6 NA