【问题标题】:Use if statement in apply to create new variable [duplicate]在 apply 中使用 if 语句创建新变量 [重复]
【发布时间】:2020-10-07 01:54:27
【问题描述】:

我有一个带有 ID 号、性别和年龄的 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}) 我收到同样的警告。

【问题讨论】:

    标签: r for-loop sapply


    【解决方案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
    

    【讨论】:

      【解决方案2】:

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

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

      【讨论】:

      • 谢谢,这是一个简单的解决方案。不,别担心我的 data.frame 不叫data.frame!作为学习者,了解如何使用for 循环或sapply 进行此类操作会很有帮助
      • 两种可能性:df$Score &lt;- sapply(df$Sex, function(i) as.numeric(i == "Male"))for (i in 1:nrow(df)) { df$Score[i] &lt;- as.numeric(df$Sex[i] == "Male") }。但是尽量避免for-loops,通常有更好的方法来完成工作。
      • 再次感谢。我还创建了一个age_score 变量。为此,我使用了for 循环:for (i in 1:nrow(eligible)) {if (eligible$Age[i] &gt; 80) {eligible$age_score[i] = 6} else if (eligible$Age[i] &gt; 70) {eligible$age_score[i] = 4} else if (eligible$Age[i] &gt; 60) {eligible$age_score[i] = 2} else if (eligible$Age[i] &gt;50) {eligible$age_score[i] =1} else {eligible$age_score[i] = 0}} 这里有for 循环的替代方案吗?
      • 使用dplyr 很容易做到这一点:eligible %&gt;% mutate(age_score = case_when(Age &gt; 80 ~ 6, Age &gt; 70 ~ 4, Age &gt; 60 ~ 2, Age &gt; 50 ~ 1, TRUE ~ 0))mutate-函数创建新变量。 case_when 是嵌套 if-else 语句的更好版本,~ 的左侧给出条件,右侧给出值。
      • 看看R for Data Science。这很好地介绍了如何使用 R。
      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2014-04-11
      • 2020-04-16
      • 1970-01-01
      • 2020-10-29
      • 1970-01-01
      相关资源
      最近更新 更多