R语言 如何基于数据框中的现有列在新列中添加数据?

ntjbwcob  于 2023-03-27  发布在  其他
关注(0)|答案(2)|浏览(225)

我有一个这样的数据框。

DF <- data.frame(names = c("john", "bob", "frank", "bill", "sam"),
                 pets  = c("dog", "cat", "mouse", "horse", "bird"))

我想根据第二列(pets)中的数据在两个不同的列中添加新数据。
我写了这两行代码,它能工作

DF$color[DF$pets == "dog"] <- "red"
DF$ID[DF$pets == "dog"] <- 1

我怎么能把它们放在一个语句中呢?

yfwxisqw

yfwxisqw1#

使用

DF[DF$pets == "dog", c("color", "ID")] <- list("red", 1)

或执行连接

library(dplyr)
 left_join(DF, tibble(pets = "dog", color = "red", ID = 1))
nhaq1z21

nhaq1z212#

技巧是用data.framemerge
您可以添加一行

d1 <- data.frame(pets='dog',
                 color='red', 
                 ID=1)

merge(DF, d1, all=TRUE)
#    pets names color ID
# 1  bird   sam  <NA> NA
# 2   cat   bob  <NA> NA
# 3   dog  john   red  1
# 4 horse  bill  <NA> NA
# 5 mouse frank  <NA> NA

和多行(即使DF中没有owl)。

d2 <- data.frame(pets=c('dog', 'bird', 'owl'),
                 color=c('red', 'green', 'blue'), 
                 ID=c(1, 2, 3))

merge(DF, d2, all=TRUE)
#    pets names color ID
# 1  bird   sam green  2
# 2   cat   bob  <NA> NA
# 3   dog  john   red  1
# 4 horse  bill  <NA> NA
# 5 mouse frank  <NA> NA
# 6   owl  <NA>  blue  3

数据框自动按pets合并,因为它是共享列名。查看?merge以获得其他选项。结果按pets按字母顺序排序,使用merge(., sort=FALSE)关闭该行为。

  • 数据:*
DF <- structure(list(names = c("john", "bob", "frank", "bill", "sam"
), pets = c("dog", "cat", "mouse", "horse", "bird")), class = "data.frame", row.names = c(NA, 
-5L))

相关问题