R中的If / Else语句

时间:2018-10-21 20:36:33

标签: r

我在R中有两个数据框:

city         price    bedroom   
San Jose     2000        1          
Barstow      1000        1          
NA           1500        1          

要重新创建的代码:

data = data.frame(city = c('San Jose', 'Barstow'), price = c(2000,1000, 1500), bedroom = c(1,1,1))

和:

Name       Density
San Jose    5358
Barstow      547

要重新创建的代码:

population_density = data.frame(Name=c('San Jose', 'Barstow'), Density=c(5358, 547));

我想根据条件在city_type数据集中创建一个名为data的附加列,因此,如果城市人口密度高于1000,则为城市,低于1000的为郊区,并且NA是NA。

city         price    bedroom   city_type   
San Jose     2000        1        Urban
Barstow      1000        1        Suburb
NA           1500        1          NA

我正在使用for循环进行条件流:

for (row in 1:length(data)) {
    if (is.na(data[row,'city'])) {
        data[row, 'city_type'] = NA
    } else if (population[population$Name == data[row,'city'],]$Density>=1000) {
        data[row, 'city_type'] = 'Urban'
    } else {
        data[row, 'city_type'] = 'Suburb'
   }
}

for循环在原始数据集中运行时没有错误,观察到20000多个;但是,它会产生很多错误的结果(大部分情况下会产生NA)。

这里出了什么问题?如何才能更好地达到预期的效果?

2 个答案:

答案 0 :(得分:4)

对于这种类型的加入/过滤/变异工作流程,我非常喜欢print(map(lambda x: x * 10, [5,12,31,7,25])) 管道。所以这是我的建议:

dplyr

输出:

library(dplyr)

# I had to add that extra "NA" there, did you not? Hm...
data <- data.frame(city = c('San Jose', 'Barstow', NA), price = c(2000,1000, 500), bedroom = c(1,1,1))
population <- data.frame(Name=c('San Jose', 'Barstow'), Density=c(5358, 547));

data %>% 
  # join the two dataframes by matching up the city name columns
  left_join(population, by = c("city" = "Name")) %>% 
  # add your new column based on the desired condition  
  mutate(
    city_type = ifelse(Density >= 1000, "Urban", "Suburb")
  )

答案 1 :(得分:2)

使用ifelsecity_type中创建population_density,然后我们使用match

population_density$city_type=ifelse(population_density$Density>1000,'Urban','Suburb')
data$city_type=population_density$city_type[match(data$city,population_density$Name)]
data
      city price bedroom city_type
1 San Jose  2000       1     Urban
2  Barstow  1000       1    Suburb
3     <NA>  1500       1      <NA>