gpt4 book ai didi

r - 根据变量/NA : In R 的存在总结数据帧

转载 作者:行者123 更新时间:2023-12-02 09:28:12 25 4
gpt4 key购买 nike

对于示例数据框:

  df <- structure(
list(
country = structure(
c(1L, 1L, 1L, 2L, 2L, 2L,
3L, 3L, 3L, 3L),
.Label = c("Austria", "France", "UK"),
class = "factor"
),
id = 1:10,
region.0 = structure(
c(1L, 1L, 1L, 2L, 2L, 2L,
3L, 3L, 3L, 3L),
.Label = c("AT", "FR", "UK"),
class = "factor"
),
region.1 = structure(
c(1L, 1L, 2L, 3L, 3L, 3L, 4L, 4L, 6L,
5L),
.Label = c("AT1", "AT2", "FR1", "UK1", "UK4", "UK6"),
class = "factor"
),
region.2 = structure(
c(1L, 1L, 2L, 3L, 4L, 5L, NA, NA, NA,
NA),
.Label = c("AT11", "AT21", "FR12", "FR14", "FR19"),
class = "factor"
),
region.3 = structure(
c(NA, NA, NA, 1L, 2L, 3L, NA, NA, NA,
NA),
.Label = c("FR121", "FR142", "FR196"),
class = "factor"
)
),
.Names = c("country",
"id", "region.0", "region.1", "region.2", "region.3"),
class = "data.frame",
row.names = c(NA, -10L)
)

我想生成一个汇总表,详细说明我的 df 数据框中提供了哪些国家/地区的区域级数据。

区域数据可在region.1、region.2或region.3中获取。数据要么可用,要么列为“NA”。无论该国家/地区的“id”如何,区域数据的可用级别都是相同的。

我想要在数据框中的最终结果如下所示:

  country region.1 region.2 region.3
1 Austria Yes Yes No
2 France Yes Yes Yes
3 UK Yes No No

有人可以建议一个特定的包或代码来帮助我吗?

最佳答案

我们可以使用data.table。将“data.frame”转换为“data.table”(setDT(df)),按“国家/地区”分组,在.SDcols中指定要比较的列,我们使用lapply循环遍历各列,然后检查ifall列中的值为“NA”,然后我们得到“No”,如下所示输出或else得到“Yes”

library(data.table)
setDT(df)[, lapply(.SD, function(x) if(all(is.na(x)))
"No" else "Yes") , country, .SDcols=region.1:region.3]
# country region.1 region.2 region.3
#1: Austria Yes Yes No
#2: France Yes Yes Yes
#3: UK Yes No No

或者使用dplyr,我们可以在按“国家”(group_by)分组后实现相同的逻辑。

library(dplyr)
df %>%
group_by(country) %>%
summarise_each(funs(if(all(is.na(.))) "No"
else "Yes"), matches("^region\\.[1-9]"))
#country region.1 region.2 region.3
# (fctr) (chr) (chr) (chr)
#1 Austria Yes Yes No
#2 France Yes Yes Yes
#3 UK Yes No No

关于r - 根据变量/NA : In R 的存在总结数据帧,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/35773493/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com