R 使用 grep 清理列表列表中的列
R use grep to clean column in list of lists
我有一个大型数据集存储为列表列表,可以这样简化:
list1 <- list(1,"bob", "age=14;years")
list2 <- list(2,"bill", "age=24;years")
list3 <- list(3,"bert", "age=36;years")
data.list <- list(list1, list2, list3)
我希望清理第三列,以便我只有年龄的数值。
这可以通过 return 一个新列表的以下函数来完成:
clean <- function(x){
x <- as.numeric(gsub('.*age=(.*?);.*','\1', x[3]))
}
data.age <- lapply(data.list, clean)
但是我怎么可能
a) 直接清理列到 return 值
或
b) 将原始列 [3]
替换为 data.age
列?
您需要 return 将列表返回到您的函数中,因此将您的函数修改为:
clean <- function(x){
x[[3]] <- as.numeric(gsub('.*age=(.*?);.*','\1', x[[3]]))
x
}
data.age <- lapply(data.list, clean)
应该可以解决问题。
我有一个大型数据集存储为列表列表,可以这样简化:
list1 <- list(1,"bob", "age=14;years")
list2 <- list(2,"bill", "age=24;years")
list3 <- list(3,"bert", "age=36;years")
data.list <- list(list1, list2, list3)
我希望清理第三列,以便我只有年龄的数值。 这可以通过 return 一个新列表的以下函数来完成:
clean <- function(x){
x <- as.numeric(gsub('.*age=(.*?);.*','\1', x[3]))
}
data.age <- lapply(data.list, clean)
但是我怎么可能
a) 直接清理列到 return 值
或
b) 将原始列 [3]
替换为 data.age
列?
您需要 return 将列表返回到您的函数中,因此将您的函数修改为:
clean <- function(x){
x[[3]] <- as.numeric(gsub('.*age=(.*?);.*','\1', x[[3]]))
x
}
data.age <- lapply(data.list, clean)
应该可以解决问题。