根据R中另一个数据框中的列将值添加到数据框中

时间:2020-09-27 15:37:43

标签: r dataframe

嘿!

我有一个包含三列的数据集:值,国家和种类。例如,可以这样创建的数据框:

Value <- c(1,2,3,4,2,6,3,5)
Country <- c("Country A", "Country A", "Country A", "Country B", "Country B", "Country B", "Country B", "Country B")
Species <- c("Species A", "Species B", "Species C", "Species A", "Species B", "Species C", "Species D", "Species E")
p <- data.frame(Value, Country, Species)

然后,除了第一列之外,我还有一个空的数据框。像这样创建:

Species2 <- levels(p$Species)
Country2 <- levels(p$Country)
x <- data.frame(Country2)
x[Species2] <- NA

现在,我正在寻找一种方法来组合这两个数据集,以便可以根据国家和物种的名称将数据集p中的值放入数据集x中的空单元格中。例如,国家/地区A和物种A的值是1(在数据框p中),因此我希望物种A的列中的单元格中的数据框x中的值为1,第一列表示国家/地区A。

我希望这个问题有道理,希望有人可以帮助我! 谢谢!

3 个答案:

答案 0 :(得分:1)

如果数据集不同,则可以将其整形为长x,然后使用pleft_join()合并。之后,重塑为宽。接下来使用tidyverse函数的代码:

library(tidyverse)
#Code
newx <- x %>% pivot_longer(-Country2) %>%
  rename(Country=Country2,Species=name) %>%
  left_join(p) %>%
  mutate(value=Value) %>% select(-Value) %>% 
  pivot_wider(names_from = Species,values_from=value) %>%
  rename(Country2=Country)
 

输出:

# A tibble: 2 x 6
  Country2  `Species A` `Species B` `Species C` `Species D` `Species E`
  <fct>           <dbl>       <dbl>       <dbl>       <dbl>       <dbl>
1 Country A           1           2           3          NA          NA
2 Country B           4           2           6           3           5

答案 1 :(得分:1)

base R中,我们可以轻松做到这一点

xtabs(Value ~ Country + Species, p)

-输出

#           Species
#Country     Species A Species B Species C Species D Species E
#  Country A         1         2         3         0         0
#  Country B         4         2         6         3         5

答案 2 :(得分:1)

也许您可以尝试使用reshape将长数据帧转换为宽数据帧

> reshape(p,direction = "wide",idvar = "Country",timevar = "Species")
    Country Value.Species A Value.Species B Value.Species C Value.Species D
1 Country A               1               2               3              NA
4 Country B               4               2               6               3
  Value.Species E
1              NA
4               5