简体   繁体   English

使用不同的列应用功能-R

[英]Applying Function Using Different Columns - R

I have an array in r that has thousands of rows and three different columns. 我在r中有一个包含数千行和三个不同列的数组。 For each row in the array, I want to change the first column based on the first column and third column. 对于数组中的每一行,我想根据第一列和第三列更改第一列。 Specifically, if the number in the third column is larger than the number in the first column, it should return a 1, if the number in the third column is smaller than the number in the first column, it should return a 0, if they are the same number it should randomly choose 1 or 0. 具体来说,如果第三列中的数字大于第一列中的数字,则应返回1;如果第三列中的数字小于第一列中的数字,则应返回0。是相同的数字,应随机选择1或0。

    temp[,1]<- sapply(
                        temp[,1],
                        function(score){
                           if(temp[,3]>score){1}
                           else if(temp[,3]<score){0}else
                           else if(temp[,3]==score){sample(0:1,1)}})

This is the code I have so far but it isn't quite working, I think when I call "temp[,3]" it returns a vector with all the rows in the third column, I just want the one entry in that row corresponding to the row I get with "score". 这是我到目前为止的代码,但是不能正常工作,我认为当我调用“ temp [,3]”时,它返回一个包含第三列中所有行的向量,我只希望该行中的一个条目对应于我通过“得分”获得的行。

也可以使用算术代替条件来完成:

rbinom(nrow(temp), 1, (temp[,1]<temp[,3])+(temp[,1]==temp[,3])*0.5)

Use ifelse : 使用ifelse

ifelse(temp[,1] < temp[,3], 1, # test condition 1, give 1 if TRUE
       ifelse(temp[,1] > temp[,3], 0, # condition 1 is FALSE, test condition 2
              rbinom(dim(temp)[1],1,.5))) # condition 2 is FALSE, return random

EDIT : ifelse works by testing a condition, then doing something if that condition is TRUE or something else if it is FALSE . 编辑ifelse通过测试条件来工作,然后在条件为TRUE执行某些操作,或者在条件为FALSE You have three conditions, so instead of providing a value for when the first condition ( temp[,1] < temp[,3] ) is FALSE , this provides a second ifelse statement, which tests your second condition (temp[,1] > temp[,3]) . 您具有三个条件,因此不必提供第一个条件( temp[,1] < temp[,3] )为FALSEifelse提供第二条ifelse语句来测试您的第二个条件(temp[,1] > temp[,3])

All remaining cases are then generated randomly using rbinom . 然后使用rbinom随机生成所有剩余的案例。 This has to be a vector rather than draw because otherwise all of your rows that do not meet conditions 1 and 2 would be given the same random draw. 这必须是矢量而不是绘图,因为否则所有不满足条件1和2的行都将被赋予相同的随机绘图。 If you try: 如果你试试:

ifelse(temp[,1]<temp[,3],1,ifelse(temp[,1]>temp[,3],0,rbinom(1,1,.5)))

You'll see that all rows where temp[,1]==temp[,3] have the same value. 您会看到temp[,1]==temp[,3]所有行都具有相同的值。 It would be the same as just doing something like: 就像做类似的事情一样:

ifelse(temp[,1]<temp[,3],1,ifelse(temp[,1]>temp[,3],0,2))

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

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