在 apply 中使用 if 语句创建新变量

Use if statement in apply to create new variable

我有一个 data.frame,其中包含身份证号码、性别和年龄。我想创建一个基于性别和年龄的分数列。首先我想给所有男性打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(df)) {if (df$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(df,function(x)if (df$Sex == "M") {1} else {0}) 我收到相同的警告。

数据:

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

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

df %>%
  mutate(sex_score = as.integer(Sex == "M"))