使用if语句来创建新变量

问题描述 投票:-1回答:2

我有一个ID为ID,性别和年龄的数据框。我想创建一个基于性别和年龄得分的列。首先,我想为所有男性分配1分,M

ID   Sex   Age   sex_score
1    M     72    1
2    M     65    1
3    F     55    0

我已经尝试过for循环和sapply,但是我还是一个初学者,并不真正知道如何使用它们。这些是我的尝试:

sex_score <- for (i in 1:nrow(data.frame)) {if (data.frame$Sex == "M") {1} else {0}}我收到警告

In if (eligible$Sex == "M") {... :
the condition has length > 1 and only the first element will be used 

我也尝试过Sex_score <- sapply(eligible,function(x)if (eligible$Sex == "M") {1} else {0})我收到相同的警告。

r for-loop sapply
2个回答
1
投票

数据:

df <- data.frame(
  Sex = c("Male", "Male", "Female")
)

解决方案:

df$Score <- ifelse(df$Sex=="Male", 1, 0)

结果:

df
     Sex Score
1   Male     1
2   Male     1
3 Female     0

0
投票

我建议您使用软件包tidyverse。如果您的data.frame命名为df(请不要命名为data.frame data.frame),请尝试:

df %>%
  mutate(sex_score = as.integer(Sex == "M"))
© www.soinside.com 2019 - 2024. All rights reserved.