简体   繁体   English

如何在 R 编程中使用 mutate?

[英]How to use mutate in R programming?

The question goes like this.问题是这样的。 Use mutate to create a dollars_per_day variable, which is defined as gdp/population/365.使用 mutate 创建一个 Dollar_per_day 变量,定义为 gdp/population/365。 Create the dollars_per_day variable for African countries for the year 2010. Remove any NA values.为 2010 年的非洲国家/地区创建 Dollars_per_day 变量。删除任何 NA 值。 Save the mutated dataset as daydollars.将变异数据集保存为 daydollars。 My codes are below, is it possible to combine filter and mutate using mutate?我的代码如下,是否可以使用 mutate 组合过滤器和变异? Thanks!谢谢!

#I used this code
library(dplyr) 
library(dslabs) 
data(gapminder) 
daydollars <- mutate(gapminder,continent=="Africa", year=2010, dollars_per_day=gdp/population/365,na.rm = TRUE) 
daydollars

You can use something like this:你可以使用这样的东西:

 library(dplyr) library(dslabs) data(gapminder) daydollars <- mutate( gapminder, dollars_per_day= ifelse(is.na(gdp), 0, as.numeric(year==1960) * as.numeric(continent=="Africa") * gdp/population/365) ) daydollars

The idea is to apply the filter by multiplying an expression with vectors of True/False.这个想法是通过将表达式与真/假向量相乘来应用过滤器。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM