R - 在现有数据集中创建新变量

时间:2018-03-05 23:26:48

标签: r variables

我正在处理一个包含有关泰坦尼克号乘客信息的数据集。

在第一个代码块中,我将原始数据集< titanic1'存储到一个名为titanic_age_groups的新数据集中。然后,我正在创建一个新变量child_or_adult,将每位乘客分类为一个年龄组。

titanic_age_groups <- titanic1

titanic_age_groups %>% 
  mutate(child_or_adult = ifelse(test = age <= 9 & !is.na(age), 
                                 yes = "child", 
                                 no = "adult"))

到目前为止,代码工作正常。然后,我正在创建新的变量,以便能够找出幸存的孩子数和总孩子数。 然后计算(幸存者子女数/总儿童数)。但是当我尝试运行下一个代码块时,我收到了这个错误:

children <- filter(titanic_age_groups, child_or_adult == 'child')
Error in filter_impl(.data, quo) : 
  Evaluation error: object 'child_or_adult' not found.


children <- filter(titanic_age_groups, child_or_adult == 'child')
children
totalC <- count(children, c('name'))
totalC
totalC <- as.numeric(totalC)
survivorsC <- filter(children, c(survived == 1))
survivorsC
totalsurvC <- count(survivorsC, c('survived'))
totalsurvC
totalsurvC <- as.numeric(totalsurvC)

childP <- (totalsurvC/totalC)
childP

我知道代码:

children <- filter(titanic_age_groups, child_or_adult == 'child')
    children
    totalC <- count(children, c('name'))
    totalC
    totalC <- as.numeric(totalC)
    survivorsC <- filter(children, c(survived == 1))
    survivorsC
    totalsurvC <- count(survivorsC, c('survived'))
    totalsurvC
    totalsurvC <- as.numeric(totalsurvC)

    childP <- (totalsurvC/totalC)
    childP

起作用,因为我曾经发现类似的情况与幸存的男女。但我不知道为什么R没有认识到新的变量&#39; child_or_adult&#39;

1 个答案:

答案 0 :(得分:0)

您的mutate调用需要分配回数据帧。仅使用管道不会修改全局环境中的数据。如果用以下内容替换第一个块,它将正常工作。

titanic_age_groups <- titanic1

titanic_age_groups <- titanic_age_groups %>% 
  mutate(child_or_adult = ifelse(test = age <= 9 & !is.na(age), 
                                 yes = "child", 
                                 no = "adult"))