如何将函数应用于R中数据帧的每一行?

6 loops for-loop r function lapply

我想将给定的函数应用于数据帧的每一行并使用行的另一个值作为输入参数/参数:

Model <- c("H5", "H5", "H5","H4")
Length <- c(6, 6, 6, 6)
Code <- c("030299", "010121","030448","030324")

df <- data.frame(Model,Length,Code)


Model   Length   Code
HS5       6     030299
HS5       6     010121
HS5       6     030448
HS4       6     030324
Run Code Online (Sandbox Code Playgroud)

我想将以下代码应用于每一行并生成结果作为新列

Library(concordance)

concord(sourcevar = (each row of 'Code' column), origin = as.character(character in 'Model' column) , destination = "HS4", dest.digit = as.numeric(number in 'Length' column), all = F))
Run Code Online (Sandbox Code Playgroud)

文档第 6 页

Maë*_*aël 2

apply您可以在行 ( ) 上使用MARGIN = 1

apply(df, MARGIN = 1, function(x) concord(sourcevar = x[3], origin = x[1], destination = "HS4", dest.digit = x[2], all = F))
Run Code Online (Sandbox Code Playgroud)

但是,这不起作用,因为“HS4”和“HS4”之间没有转换字典,因此您只能apply在非 HS4 的行上使用:

df$New <- df$Code
df[df$Model != "HS4", ]$New <- apply(df[df$Model != "HS4", ], 1, \(x) concord(sourcevar = x[colnames(df) == "Code"], 
                                               origin = x[colnames(df) == "Model"], destination = "HS4", 
                                               dest.digit = x[colnames(df) == "Length"], all = F))

  Model Length   Code    New
1   HS5      6 030299 030289
2   HS5      6 010121 010121
3   HS5      6 030448 030449
4   HS4      6 030324 030324
Run Code Online (Sandbox Code Playgroud)