In R, how to replace values in multiple columns with a vector of values equal to the same width?

jna*_*m27 5 replace r vector multiple-columns dataframe

I am trying to replace every row's values in 2 columns with a vector of length 2. It is easier to show you.

First here is a some data.

set.seed(1234) 
x<-data.frame(x=sample(c(0:3), 10, replace=T))
x$ab<-0 #column that will be replaced
x$cd<-0 #column that will be replaced
Run Code Online (Sandbox Code Playgroud)

The data looks like this:

   x ab cd
1  0  0  0
2  2  0  0
3  2  0  0
4  2  0  0
5  3  0  0
6  2  0  0
7  0  0  0
8  0  0  0
9  2  0  0
10 2  0  0
Run Code Online (Sandbox Code Playgroud)

Every time x=2 or x=3, I want to ab=0 and cd=1.

My attempt is this:

x[with(x, which(x==2|x==3)), c(2:3)] <- c(0,1)
Run Code Online (Sandbox Code Playgroud)

Which does not have the intended results:

   x ab cd
1  0  0  0
2  2  0  1
3  2  1  0
4  2  0  1
5  3  1  0
6  2  0  1
7  0  0  0
8  0  0  0
9  2  1  0
10 2  0  1
Run Code Online (Sandbox Code Playgroud)

Can you help me?

mri*_*rip 8

它无法正常工作的原因是因为R在列主要布局中存储矩阵和数组.当你为较长的数组分配一个较短的数组时,R循环通过较短的数组.例如,如果你有

x<-rep(0,20)
x[1:10]<-c(2,3)
Run Code Online (Sandbox Code Playgroud)

然后你最终得到了

 [1] 2 3 2 3 2 3 2 3 2 3 0 0 0 0 0 0 0 0 0 0
Run Code Online (Sandbox Code Playgroud)

在你的情况下发生的是,通过在向量中循环,通过列填充x等于2或3的子数组c(0,1).我不知道有什么简单的方法可以改变这种行为.

这里最简单的方法可能就是一次只填写一列.或者,你可以做这样的事情:

indices<-with(x, which(x==2|x==3))
x[indices,c(2,3)]<-rep(c(0,1),each=length(indices))
Run Code Online (Sandbox Code Playgroud)


Fra*_*ank 7

另一种选择:使用data.table,这是一个单行:

require(data.table)
DT <- data.table(x)
DT[x%in%2:3,`:=`(ab=0,cd=1)]
Run Code Online (Sandbox Code Playgroud)

原始答案:您可以传递行列对矩阵:

ijs <- expand.grid(with(x, which(x==2|x==3)),c(2:3))
ijs <- ijs[order(ijs$Var1),]

x[as.matrix(ijs)] <- c(0,1)
Run Code Online (Sandbox Code Playgroud)

产量

   x ab cd
1  0  0  0
2  2  0  1
3  2  0  1
4  2  0  1
5  3  0  1
6  2  0  1
7  0  0  0
8  0  0  0
9  2  0  1
10 2  0  1
Run Code Online (Sandbox Code Playgroud)

我的原始答案适用于我的电脑,但不是评论者.