简体   繁体   English

如何使用另一列中的值和条件填充列

[英]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))

data数据

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.

相关问题 根据条件用另一列中的值填充列 - fill column with values in another columns based on their conditions 如何根据另一列中的条件更改数据框的某一列中的值? - How to change values in a column of a data frame based on conditions in another column? 如何根据来自不同长度的数据帧的条件填充数据框中的列? - How to fill a column in a dataframe based on conditions from a dataframe with different length? 如何根据 R 中另一列的值填写空白 - How to fill in blanks based off another column's values in R 根据另一列中的条件将一列中的值设置为 NA - Setting values to NA in one column based on conditions in another column 如何使用dplyr根据另一列的不同值在新列中填充不同的值? - How to fill different values in a new column based on different values of another column using dplyr? Q-如何通过R中的两个条件基于行值在data.frame中填充新列 - Q-How to fill a new column in data.frame based on row values by two conditions in R 如何用 dplyr 的另一列的值填充每第 n 行? - How to fill in every nth row with values from another column with dplyr? 如何使用R中另一个数据帧的值填充列 - How to fill a column using values from another dataframe in R 在 R 中,如何根据两个条件对一列的值求和,并按另一列值分组? - How to sum values of one column, based on two conditions, grouped by another column value, in R?
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM