简体   繁体   English

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

[英]Subset data frame filling certain columns with NA in R

I would like to subset data and fill all rows in certain columns with NA values. 我想对数据进行子集化,并用NA值填充某些列中的所有行。 It is easier to follow with an example: 举个例子比较容易:

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

to return this: 返回此:

在此处输入图片说明

I know that this obviously won't work since i don't have these NA columns in x. 我知道这显然不起作用,因为我在x中没有这些NA列。 But is there some way to do this? 但是有什么方法可以做到这一点吗? Perhaps paste two subsets together with NA columns between? 也许将两个子集与它们之间的NA列粘贴在一起?

As recommended by @konvas, just use cbind . 按照@konvas的建议,只需使用cbind

Here's a worked example: 这是一个可行的示例:

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM