简体   繁体   English

R 根据另一列中的值为列赋值

[英]R Assign value to column according to value in another column

I have a data frame like this我有一个这样的数据框

 NAME       DIST    
 A          0           
 A          1           
 A          100         
 A          2           
 A          1           
 A          4           
 A          500         
 A          1           
 A          1           

What I want to do is to find an efficient way of creating a new column NEWNAME such that if DIST > 100 it contains aa name that is equal for all the previous rows我想要做的是找到一种创建新列 NEWNAME 的有效方法,这样,如果 DIST > 100,它包含的名称对于所有先前的行都相同

 NAME       DIST     NEWNAME
 A          0           A
 A          1           A
 A          100         A
 A          2           A2
 A          1           A2
 A          4           A2
 A          500         A3
 A          1           A3
 A          1           A3

I have done it using a for loop but I was looking for a more efficient solution in R style.我已经使用 for 循环完成了它,但我正在寻找 R 风格的更有效的解决方案。 Below my code using a for loop在我的代码下方使用 for 循环

k <- 0
for(l in 1:length(df$NAME)){
       if(df$DIST[l] >= 100){
                k <- k+1;
                df$NEWNAME[(l):length(df$NAME)] <- paste(df$NAME,k,sep="")
        }
    }

Thanks in advance提前致谢

You can do this to create your new column:您可以这样做来创建新列:

df$NEWNAME=paste0("A", cumsum(0+df$DIST>=100))

I used your data as df and also assumed you meant superior or equal to 100:我将您的数据用作df并假设您的意思是优于或等于100:

df=data.frame("NAME"=rep("A", 9), "DIST"=c(0,1,100,2,1,4,500,1,1))

EDIT编辑

If you need to start the new names at the row N+1 of the distance>100, you can do this after:如果您需要在距离>100 的第 N+1 行开始新名称,您可以在之后执行此操作:

df$NEWNAME2 = lag(df$NEWNAME, n=1, default="A0")
####   NAME DIST NEWNAME NEWNAME2
#### 1    A    0      A0       A0
#### 2    A    1      A0       A0
#### 3    A  100      A1       A0
#### 4    A    2      A1       A1
#### 5    A    1      A1       A1

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

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