在R中,如何用等于相同宽度的值的向量替换多列中的值? [英] In R, how to replace values in multiple columns with a vector of values equal to the same width?

查看:175
本文介绍了在R中,如何用等于相同宽度的值的向量替换多列中的值?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我试图用长度为2的向量替换2列中的每一行的值。更容易显示。



首先是一些数据。

  set.seed(1234)
x< -data.frame(x = sample(c(0:3 ),10,replace = T))
x $ ab< -0 #column将被替换
x $ cd< -0 #column将被替换

数据如下所示:

  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

每次x = 2或x = 3,我想要ab = 0和cd = 1。



我的尝试是这样:

  x [with(x,which(x == 2 | x == 3)),c(2:3 )]<  -  c(0,1)

哪些没有预期的结果: p>

  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
pre>

你能帮我吗?

解决方案

因为R在列主要布局中存储矩阵和数组。而当您将较短的数组分配给较长的数组时,R会循环使用较短的数组。例如,如果您有

  x< -rep(0,20)
x [1:10]< c(2,3)

然后你最终得到

  [1] 2 3 2 3 2 3 2 3 2 3 0 0 0 0 0 0 0 0 0 0 
pre>

您的情况发生的是,x等于2或3的子数组通过循环遍历向量 c(0,1)。我不知道改变这种行为的任何简单的方法。



可能这里最简单的一件事是简单地填写一个列。或者你可以这样做:

 索引< -with(x,which(x == 2 | x == 3))
x [indices,c(2,3)]< -rep(c(0,1),each = length(indices))


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

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

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)

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

Can you help me?

解决方案

The reason it doesn't work as you want is because R stores matrices and arrays in column-major layout. And when you a assign a shorter array to a longer array, R cycles through the shorter array. For example if you have

x<-rep(0,20)
x[1:10]<-c(2,3)

then you end up with

 [1] 2 3 2 3 2 3 2 3 2 3 0 0 0 0 0 0 0 0 0 0

What is happening in your case is that the sub-array where x is equal to 2 or 3 is being filled in column-wise by cycling through the vector c(0,1). I don't know of any simple way to change this behavior.

Probably the easiest thing to do here is simply fill in the columns one at a time. Or, you could do something like this:

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

这篇关于在R中,如何用等于相同宽度的值的向量替换多列中的值?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆