[英]Why data.frame column is not changing in R
I have following data frame: 我有以下数据框:
ddf
vnum1 vnum2
1 1 0.6380312
2 1 0.1737218
3 1 0.3528707
4 1 0.8670922
5 1 0.6498109
>
>
> str(ddf)
'data.frame': 5 obs. of 2 variables:
$ vnum1: num 1 1 1 1 1
$ vnum2: num 0.638 0.174 0.353 0.867 0.65
>
I want to change all values of vnum1 from 1 to 4. 我想将vnum1的所有值从1更改为4。
Why following do not work: 为什么以下操作无效:
> rbind(ddf, ddf[,1]=4)
Error: unexpected '=' in "rbind(ddf, ddf[,1]="
Following adds only one number and that too to both columns. 以下仅将一个数字加到两列。 It is obviously not working correctly.
它显然无法正常工作。
> rbind(ddf, (ddf[,1]=4))
vnum1 vnum2
1 1 0.6380312
2 1 0.1737218
3 1 0.3528707
4 1 0.8670922
5 1 0.6498109
6 4 4.0000000
There are two problems here. 这里有两个问题。
The code doesn't work because =
as you're using it in the argument list of a function is incorrect. 该代码不起作用,因为在函数的参数列表中使用
=
不正确。 In rbind
, =
is used to assign names to the arguments. 在
rbind
, =
用于为参数分配名称。
To see this, try rbind(ddf, ddf[,1] <- 4)
versus rbind(ddf, ddf[,1]=4)
为此,请尝试
rbind(ddf, ddf[,1] <- 4)
与rbind(ddf, ddf[,1]=4)
Also try rbind(ddf, X = 3)
and look at the row names. 也尝试
rbind(ddf, X = 3)
并查看行名。
rbind
is a row bind function. rbind
是一个行绑定函数。 So when you call rbind(ddf, ddf[,1]=4)
you are trying to add a new row filled with 4's to the bottom of ddf
. 因此,当您调用
rbind(ddf, ddf[,1]=4)
您尝试在ddf
的底部添加一个新行,其中填充了4。
That said, to replace all the values in the first column with 4, you can just use ddf[,1]=4
, like you have in your rbind
call, or you can also do 就是说,要将第一列中的所有值替换为4,您可以像使用
rbind
调用一样使用ddf[,1]=4
,或者也可以
ddf$vnum1 <- 4L
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.