下面你可以在R中重新创建我的数据。我想基于两个单独的列生成一系列数字。在这个真实数据示例中,我的列名是:
df= or10x1BC
"Tank" "Core" "BCl" "BCu" "Mid" "TL" "SL"
我希望使用BCu
和BCl
每行中的值来生成0.001的序列。例如seq(BCu[1], BCl[1], 0.001)
将根据每个中的第一行生成一个序列,我希望对列表中的每一行都有这个功能。
最终,我的函数中将使用此序列来生成序列的平均值,即mean(function(seq(Bcu[i], BCl[j], 0.001))
并添加到新列or10x1BC["meanBVF"] = mean(function(seq(Bcu[i], BCl[j], 0.001))
。
见下面的数据:
structure(list(Tank = structure(c(1L, 1L, 1L, 1L, 1L, 1L, 1L,
1L, 1L), .Label = "1", class = "factor"), Core = structure(c(1L,
1L, 1L, 2L, 2L, 2L, 3L, 3L, 3L), .Label = c("A", "B", "C"), class = "factor"),
BCl = structure(c(8L, 5L, 2L, 6L, 3L, 1L, 9L, 7L, 4L), .Label = c("17",
"18", "22", "22.3", "23", "26", "27.3", "28", "29"), class = "factor"),
BCu = structure(c(8L, 5L, 2L, 6L, 3L, 1L, 9L, 7L, 4L), .Label = c("12.5",
"13.5", "17", "17.8", "18", "22", "22.3", "23", "27.3"), class = "factor"),
Mid = structure(c(8L, 5L, 2L, 6L, 3L, 1L, 9L, 7L, 4L), .Label = c("14.75",
"15.75", "19.5", "20.05", "20.5", "24", "24.8", "25.5", "28.15"
), class = "factor"), TL = structure(c(2L, 2L, 2L, 1L, 1L,
1L, 3L, 3L, 3L), .Label = c("26", "28", "29"), class = "factor"),
SL = structure(c(4L, 4L, 3L, 2L, 4L, 3L, 1L, 4L, 3L), .Label = c("1.7",
"4", "4.5", "5"), class = "factor")), .Names = c("Tank",
"Core", "BCl", "BCu", "Mid", "TL", "SL"), row.names = c(NA, -9L
), class = "data.frame")
答案 0 :(得分:1)
mapply
与apply
或lapply
类似,但有多个参数:
首先,正如我在评论中提到的,我们需要将您的数据转换为数字。我这样做,转换除第二列以外的所有内容:
df[, -2] = lapply(df[, -2], as.character)
df[, -2] = lapply(df[, -2], as.numeric)
然后我们可以像这样使用mapply
来生成序列:
seqs = mapply(FUN = function(a, b) {
seq(from = a, to = b, by = .001)
}, a = df$BCu, b = df$BCl)
将它放在数据框中似乎很麻烦,但如果您愿意,可以这样做:
df$seqs = seqs
如果是我,我可能会将其作为数据框之外的向量列表。