使用 unite
函数时,默认情况下有一个名为 na.rm
的参数,其值为 FALSE
。
library(tidyr)
unite( all_data, Total, VoS, Value, Total.Value, na.rm = TRUE )
在原始数据中,将感兴趣的列从
factor
转换为
character
,然后执行
unite
。
library(dplyr)
all_data_new %>%
mutate_at(c(3, 6, 7, 11), as.character) %>%
unite(New, names(.)[c(3, 6, 7, 11)], na.rm = TRUE)
或者另一个选项是 coalesce
library(dplyr)
all_data %>%
transmute(Total = coalesce(!!! .))
或者在 base R
中使用pmax
函数。
do.call(pmax, c(all_data, na.rm = TRUE))
或者使用pmin
do.call(pmin, c(all_data, na.rm = TRUE))
数据
all_data <- structure(list(VoS = c(1L, NA, NA, 76L, 4L, NA, NA), Value = c(NA,
NA, 13L, NA, NA, 7L, NA), Total.Value = c(NA, 41L, NA, NA, NA,
NA, 22L)), class = "data.frame", row.names = c(NA, -7L))
all_data_new <- structure(list(Geographic.area.name = structure(c(1L, 1L, 1L,
1L, 1L, 1L), .Label = "Alabama", class = "factor"), Year = c(2009L,
2008L, 2009L, 2008L, 2009L, 2008L), Total.value.of.shipments...1.000. = c("90,530,746",
"116,401,285", "9,932,542", "9,661,432", "1,819,728", "1,744,928"
), X2007.NAICS.codes.and.NAICS.based.rollup.code = structure(c(1L,
1L, 2L, 2L, 3L, 3L), .Label = c("31-33", "311", "3111"), class = "factor"),
Meaning.of.2007.NAICS.codes.and.NAICS.based.rollup.code = structure(c(3L,
3L, 2L, 2L, 1L, 1L), .Label = c("Animal food manufacturing",
"Food manufacturing", "Manufacturing"), class = "factor"),
X.Total.value.of.shipments...1.000.. = structure(c(NA_integer_,
NA_integer_, NA_integer_, NA_integer_, NA_integer_, NA_integer_
), .Label = character(0), class = "factor"), X.Total.value.of.shipments.and.receipts.for.services...1.000.. = structure(c(NA_integer_,
NA_integer_, NA_integer_, NA_integer_, NA_integer_, NA_integer_
), .Label = character(0), class = "factor"), Relative.standard.error.for.estimate.of.total.value.of.shipments.and.receipts.for.services.... = c(NA_character_,
NA_character_, NA_character_, NA_character_, NA_character_,
NA_character_), X2012.NAICS.code = structure(c(NA_integer_,
NA_integer_, NA_integer_, NA_integer_, NA_integer_, NA_integer_
), .Label = character(0), class = "factor"), Meaning.of.2012.NAICS.code = structure(c(NA_integer_,
NA_integer_, NA_integer_, NA_integer_, NA_integer_, NA_integer_
), .Label = character(0), class = "factor"), Total.value.of.shipments.and.receipts.for.services...1.000. = c(NA_character_,
NA_character_, NA_character_, NA_character_, NA_character_,
NA_character_)), row.names = c(NA, 6L), class = "data.frame")
,
。 - akruncoalesce
也不起作用,因为我的列是因子而不是字符,值得转换吗? - Maridee Weberdput
将您的数据更新到帖子中,以便我可以正确获取结构。谢谢。 - akrunpmax
/pmin
的解决方案。 - Martin Gal