英文:
How to find the minimum from a column whose elements are list and keep its corresponding other column list valuesg?
问题
df <- data.frame(A = c(1, 2, 3, 4),
conn = c("2, 3, 4", "8, 1, 6", "4, 6, 1, 5", "5, 9, 1, 3"),
ListW = c("100, 100, 100", "60, 100, 100", "100, 50, 100, 100", "100, 10, 100, 100"))
df$ListW <- as.character(df$ListW) # 将ListW列转换为字符类型
listW_values <- strsplit(df$ListW, ", ") # 通过逗号和空格拆分ListW值
min_values <- sapply(listW_values, function(x) min(as.integer(x))) # 找到每个ListW值的最小值
# 创建新的列Nconn和minListW
df$Nconn <- sapply(listW_values, function(x) paste(df$conn[which.min(as.integer(x))], collapse = ", "))
df$minListW <- as.character(min_values)
# 移除原始的conn和ListW列
df <- df[, c("A", "Nconn", "minListW")]
df
英文:
I have data frame
df <- data.frame(A = c(1, 2, 3, 4),
conn = c("2, 3, 4", "8, 1, 6", "4, 6, 1, 5", "5, 9, 1, 3"),
ListW = c("100, 100, 100", "60, 100, 100", "100, 50, 100, 100", "100, 10, 100, 100"))
How to find the minimum from ListW
and keep its corresponding conn
value so that the output would be
df <- data.frame(A = c(1, 2, 3, 4),
Nconn = c("2, 3, 4", "8", "6", "9"),
minListW = c("100", "60", "50", "10"))
Your help would be greatly appreciated and helpful for me, others as well. I have tried with the following
df <- data.frame(A = c(1, 2, 3, 4),
conn = c("2, 3, 4", "8, 1, 6", "4, 6, 1, 5", "5, 9, 1, 3"),
ListW = c("100, 100, 100", "60, 100, 100", "100, 50, 100, 100", "100, 10, 100, 100"))
df$ListW <- as.character(df$ListW) # Convert ListW column to character type
listW_values <- strsplit(df$ListW, ", ") # Split the ListW values by comma and space
min_values <- sapply(listW_values, function(x) min(as.integer(x))) # Find the minimum value for each ListW value
答案1
得分: 2
以下是翻译好的代码部分:
library(tidyr)
library(dplyr, warn = FALSE)
df |>
separate_rows(conn, ListW, sep = ", ", convert = TRUE) |>
slice_min(ListW, n = 1, by = A) |>
summarise(across(c(conn, ListW), ~ paste0(unique(.x), collapse = ", ")), .by = A)
#> # A tibble: 4 × 3
#> A conn ListW
#> <dbl> <chr> <chr>
#> 1 1 2, 3, 4 100
#> 2 2 8 60
#> 3 3 6 50
#> 4 4 9 10
希望这对您有所帮助。如果您有其他问题,请随时提出。
英文:
One option would be to use tidyr::separate_rows
to split your columns into rows, then use e.g. dplyr::slice_min
to get the minimum(s) per group:
library(tidyr)
library(dplyr, warn = FALSE)
df |>
separate_rows(conn, ListW, sep = ", ", convert = TRUE) |>
slice_min(ListW, n = 1, by = A) |>
summarise(across(c(conn, ListW), ~ paste0(unique(.x), collapse = ", ")), .by = A)
#> # A tibble: 4 × 3
#> A conn ListW
#> <dbl> <chr> <chr>
#> 1 1 2, 3, 4 100
#> 2 2 8 60
#> 3 3 6 50
#> 4 4 9 10
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论