如何根据其他列的值创建名为 "Weight" 的第三列?当列值为 NA 时,将分配 0 权重
How to create a third column called "Weight" based on value of other column? When the column value is NA, a 0 weight would be assigned
我在一个数据框中有 4 列,基于这 2 列,需要创建第 5 列权重。当列值为 NA 时,将分配 0 权重。
假设我在 R 中有一个名为 exp 的数据框。
from to tel post
1 S01 S02 123 ABC
2 S02 S03 456 <NA>
3 S04 S05 NA XYZ
我需要创建以下权重列。
其中 weight = 10 * (tel) + 1* (post)
如果值为 NA,则为零
from to tel post weight
1 S01 S02 123 ABC 11
2 S02 S03 456 <NA> 10
3 S04 S05 NA XYZ 1
你可以这样做:
with(df, (10 * !is.na(tel)) + (1 * !is.na(post)))
[1] 11 10 1
示例数据:
df <- read.table(text = " from to tel post
1 S01 S02 123 ABC
2 S02 S03 456 <NA>
3 S04 S05 NA XYZ",
header = TRUE,
stringsAsFactors = FALSE,
na.strings = c("NA", "<NA>"))
我在一个数据框中有 4 列,基于这 2 列,需要创建第 5 列权重。当列值为 NA 时,将分配 0 权重。
假设我在 R 中有一个名为 exp 的数据框。
from to tel post
1 S01 S02 123 ABC
2 S02 S03 456 <NA>
3 S04 S05 NA XYZ
我需要创建以下权重列。 其中 weight = 10 * (tel) + 1* (post)
如果值为 NA,则为零
from to tel post weight
1 S01 S02 123 ABC 11
2 S02 S03 456 <NA> 10
3 S04 S05 NA XYZ 1
你可以这样做:
with(df, (10 * !is.na(tel)) + (1 * !is.na(post)))
[1] 11 10 1
示例数据:
df <- read.table(text = " from to tel post
1 S01 S02 123 ABC
2 S02 S03 456 <NA>
3 S04 S05 NA XYZ",
header = TRUE,
stringsAsFactors = FALSE,
na.strings = c("NA", "<NA>"))