第一次使用R:如何比较两列

时间:2019-07-09 22:53:29

标签: r

我有一个数据集“ world”,其列“ women09”包含百分比值,列“ pr_sys”包含“ yes”或“ no”。我需要找到“是”和“否”的“ women09”百分比。我不怎么比较这两列

women09 = world[["women09"]]
pr_sys = world[["pr_sys"]]
wpr = ifelse(pr_sys = "Yes",count.fields(women09))
  

ifelse(pr_sys =“ Yes”,count.fields(women09))中的错误:

     

未使用的参数(pr_sys =“是”)

ifelse(pr_sys="Yes",wpr=women09,0)
  

ifelse中的错误(pr_sys =“是”,wpr = women09,0):

     

未使用的参数(pr_sys =“是”,wpr = women09)

数据:

dput(world[1:64, c("women09", "pr_sys")])

w <- structure(list(women09 = c(NA, NA, 20.5, NA, 18.5, 8.3, 20.8, 
NA, NA, NA, 25, NA, NA, 18.1, 0.9, NA, 0, NA, NA, NA, NA, NA, 
NA, 18.6, NA, 10.5, NA, NA, 4.3, 4.1, NA, NA, NA, NA, 12, NA, 
19, NA, 7, 10.2, NA, NA, NA, NA, NA, 8.4, 3, NA, 8.9, NA, 15.2, 
10.8, 30, 10.7, NA, 18.2, 3.8, NA, NA, 16.4, NA, NA, 4, 13.2),
pr_sys = c("No", "Yes", "No", "Yes", 
"Yes", "No", "No", "No", "No", "No", "No", "No", "No", "Yes", 
"No", "No", "No", "No", "No", "No", "Yes", "No", "Yes", "No", 
"No", "No", "No", "No", "No", "No", NA, NA, "No", NA, "Yes", 
"Yes", "Yes", "No", "No", "No", "No", NA, "No", "No", NA, "No", 
"No", "No", "No", "Yes", "No", "Yes", "Yes", "No", "No", "Yes", 
"No", NA, "No", "No", "No", "Yes", "No", "Yes")), 
class = "data.frame", row.names = c(NA, -64L))

1 个答案:

答案 0 :(得分:0)

install.packages("tidyverse"); library(tidyverse) #since you said you're new to R
world <- as.data.frame(
  list(women09 = c(NA, NA, 20.5, NA, 18.5, 8.3, 20.8),
       pr_sys = c("No", "Yes", "No", "Yes","Yes", "No", "No"))
  )

world %>%
  group_by(pr_sys) %>%
  summarize(tot = sum(women09, na.rm = TRUE))

# A tibble: 2 x 2
pr_sys   tot
<fct>  <dbl>
1 No      49.6
2 Yes     18.5