[英]Add row to data.frame but only to certain columns
I wish to create a data.frame and add rows but ONLY to certain columns. 我希望创建一个data.frame并添加行,但仅添加到某些列。 I want the remaining columns to be specified as NAs.
我希望将其余列指定为NA。
What I have is as follows: 我所拥有的如下:
#create empty data frame
x=data.frame(matrix(nrow=0,ncol=3))
> x
[1] X1 X2 X3
<0 rows> (or 0-length row.names)
#The data and its corresponding columns
> y=data.frame(col=c("X1","X3"),val=c(20,30))
> y
col val
1 X1 20
2 X3 30
#select those columns (works fine)
> x[,y$col]
[1] X1 X2
<0 rows> (or 0-length row.names)
#select and create a row for those columns and corresponding values
> x[,y$col]=y$val
Error in Summary.factor(1:2, na.rm = FALSE) :
min not meaningful for factors
So the question is how would you (efficiently) create the new rows. 因此,问题是如何(有效地)创建新行。 Im guessing there ought to be a way to do it without specifying the NAs yourself.
我想应该有一种无需亲自指定NA的方法。
One of the problems is that your col
variable in y
is a factor. 问题之一是
y
中的col
变量是一个因素。 This can easily be undone: 这很容易撤消:
y=data.frame(col = c("X1","X3"), val = c(20,30), stringsAsFactors=FALSE)
Next, when you do 接下来,当你做
x[,y$col]=y$val
You don't specify a row number. 您没有指定行号。 Doing this would work though:
这样做虽然可以:
x[1,y$col] <- y$val
x
# X1 X2 X3
# 1 20 NA 30
But then you'll soon run into problems if you have other X1's and X2's to write to the x
dataframe. 但是如果您还有其他X1和X2要写入
x
数据帧,那么很快就会遇到问题。 So your algorithm might need some brush-up, unless this is really what you need. 因此,除非确实需要,否则您的算法可能需要重新刷牙。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.