使用 case_when 或 else if 语句创建两个新变量(R 编码)
Making two new variables with case_when or else if statement (R coding)
我需要对数据框进行一些更改才能创建我想要的视觉效果,但我被卡住了。下面是数据框的样子。
我想要做的是创建一个名为 'article' 的新变量。此变量的值将是 'Page' 列中 'Article Based' 个值中的 sum_pageviews 个。
同样,另一个变量将是 'info',其值将从 Page 变量中的 'Informational Based' 变为 sum_pageviews。
那么最后data frame的长度就是8,没有department的重复,这就是我想看到的。
下图是新数据框的外观。我输入了 Excel,但我想知道 R 中的代码。
--> 我想我应该从
开始
sum_views%>%group_by(department)%>%mutate
then ifelse 或 case_when 语句,但不知道。
请让我知道代码。提前致谢
这个有用吗:
library(dplyr)
library(tidyr)
df %>% mutate(article = case_when(str_detect(Page, 'Article Based') ~ sum_pageviews, TRUE ~ NA_real_),
Info = case_when(str_detect(Page, 'Information Based') ~ sum_pageviews , TRUE ~ NA_real_)) %>%
fill(article, .direction = 'down') %>% fill(Info, .direction = 'up') %>% select(-c(Page, sum_pageviews)) %>%
group_by(department) %>% filter(row_number() == 1)
# A tibble: 5 x 3
# Groups: department [5]
department article Info
<chr> <dbl> <dbl>
1 Hess 1261 8443
2 Econ 2320 15682
3 DA 2495 7262
4 CS 5096 9870
5 Theatre 2992 5764
使用的数据:
df
# A tibble: 10 x 3
Page department sum_pageviews
<chr> <chr> <dbl>
1 Article Based Hess 1261
2 Information Based Hess 8443
3 Article Based Econ 2320
4 Information Based Econ 15682
5 Article Based DA 2495
6 Information Based DA 7262
7 Article Based CS 5096
8 Information Based CS 9870
9 Article Based Theatre 2992
10 Information Based Theatre 5764
我需要对数据框进行一些更改才能创建我想要的视觉效果,但我被卡住了。下面是数据框的样子。 我想要做的是创建一个名为 'article' 的新变量。此变量的值将是 'Page' 列中 'Article Based' 个值中的 sum_pageviews 个。 同样,另一个变量将是 'info',其值将从 Page 变量中的 'Informational Based' 变为 sum_pageviews。 那么最后data frame的长度就是8,没有department的重复,这就是我想看到的。
下图是新数据框的外观。我输入了 Excel,但我想知道 R 中的代码。
--> 我想我应该从
开始sum_views%>%group_by(department)%>%mutate
then ifelse 或 case_when 语句,但不知道。 请让我知道代码。提前致谢
这个有用吗:
library(dplyr)
library(tidyr)
df %>% mutate(article = case_when(str_detect(Page, 'Article Based') ~ sum_pageviews, TRUE ~ NA_real_),
Info = case_when(str_detect(Page, 'Information Based') ~ sum_pageviews , TRUE ~ NA_real_)) %>%
fill(article, .direction = 'down') %>% fill(Info, .direction = 'up') %>% select(-c(Page, sum_pageviews)) %>%
group_by(department) %>% filter(row_number() == 1)
# A tibble: 5 x 3
# Groups: department [5]
department article Info
<chr> <dbl> <dbl>
1 Hess 1261 8443
2 Econ 2320 15682
3 DA 2495 7262
4 CS 5096 9870
5 Theatre 2992 5764
使用的数据:
df
# A tibble: 10 x 3
Page department sum_pageviews
<chr> <chr> <dbl>
1 Article Based Hess 1261
2 Information Based Hess 8443
3 Article Based Econ 2320
4 Information Based Econ 15682
5 Article Based DA 2495
6 Information Based DA 7262
7 Article Based CS 5096
8 Information Based CS 9870
9 Article Based Theatre 2992
10 Information Based Theatre 5764