[英]How to fill a column based with values and conditions from another column
I have values in column "WT" and but some of the values need to be corrected by subtracting 0.01.我在“WT”列中有值,但有些值需要通过减去 0.01 来纠正。 I want to fill a new column "FinalWT" in my dataframe(df) with corrected values where Office is "1" and the equal values where Office is "2".
我想在我的数据框(df)中填充一个新列“FinalWT”,其中 Office 为“1”的正确值和 Office 为“2”的相等值。
what I have:我有的:
Office WT
1 0.014
2 0.456
2 0.005
1 0.051
What I want to accomplish我想要完成的
Office WT FinalWT
1 0.014 0.004
2 0.456 0.456
2 0.005 0.005
1 0.051 0.041
Any help is greatly appreciated.任何帮助是极大的赞赏。 Thanks!
谢谢!
We can multiply 0.01 with logical expression so that the output would be 0.01 for TRUE and 0 otherwisee and subtract from 'WT'我们可以将 0.01 与逻辑表达式相乘,使得 output 为 TRUE 时为 0.01,否则为 0,并从“WT”中减去
library(dplyr)
df1 %>%
mutate(FinalWT = WT - 0.01 * (Office == 1))
# Office WT FinalWT
#1 1 0.014 0.004
#2 2 0.456 0.456
#3 2 0.005 0.005
#4 1 0.051 0.041
Or in base r
或在
base r
df1$FinalWT <- with(df1, WT - 0.01 * (Office == 1))
df1 <- structure(list(Office = c(1L, 2L, 2L, 1L), WT = c(0.014, 0.456,
0.005, 0.051)), class = "data.frame", row.names = c(NA, -4L))
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.