我想创建一个country_year
变量,该变量以国家和年份的出现为条件,如下所示,在我创建的这个小样本中。这意味着,如果我有两个国家/地区的年份不同,则新的country_year
变量的值将为country1_year1
、country1_year2
等。
这看起来很简单,但我是R的新手,我试图寻找针对它的不同问题,但没有成功。有人能帮我引路吗?
structure(list(id = structure(c(1, 1, 1, 2, 2, 2), format.stata = "%9.0g"),
country = structure(c("US", "US", "US", "UK", "UK", "UK"), format.stata = "%9s"),
year = structure(c(2003, 2004, 2005, 2003, 2004, 2005), format.stata = "%9.0g"),
country_year = structure(c(1, 2, 3, 4, 5, 6), format.stata = "%9.0g")), row.names = c(NA,
-6L), class = c("tbl_df", "tbl", "data.frame"))
发布于 2020-11-09 17:42:10
看起来您想要创建一个新的变量country_year
使用base R:
df$country_year <- paste0(df$country, "_", df$year)
使用dplyr:
library(dplyr)
df %>%
mutate(country_year = paste0(country,"_",year))
这为我们提供了:
id country year country_year
<dbl> <chr> <dbl> <chr>
1 1 US 2003 US_2003
2 1 US 2004 US_2004
3 1 US 2005 US_2005
4 2 UK 2003 UK_2003
5 2 UK 2004 UK_2004
6 2 UK 2005 UK_2005
发布于 2020-11-09 18:14:51
tidyverse
的一个选项是
library(dplyr)
library(tidyr)
df %>%
unite(country_year, country, year, sep="_", remove = FALSE)
-output
# A tibble: 6 x 4
# id country_year country year
# <dbl> <chr> <chr> <dbl>
#1 1 US_2003 US 2003
#2 1 US_2004 US 2004
#3 1 US_2005 US 2005
#4 2 UK_2003 UK 2003
#5 2 UK_2004 UK 2004
#6 2 UK_2005 UK 2005
https://stackoverflow.com/questions/64756487
复制