简体   繁体   English

如何将function应用到R中的每一行dataframe?

[英]How to apply function to each row of dataframe in R?

I want to apply given function to each row of dataframe and use another values of row, as input parameters/arguments:我想将给定的 function 应用于 dataframe 的每一行,并使用行的另一个值作为输入参数/参数:

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

I want to apply the following code to each row and generate the outcome as a new column我想将以下代码应用于每一行并将结果生成为新列

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))

Documentation Page 6 文档第 6 页

You can use apply on the rows ( MARGIN = 1 ).您可以在行上使用apply ( MARGIN = 1 )。

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

However, this does not work because there is no conversion dictionary between "HS4" and "HS4", so you can use apply only on the rows that are not HS4:但是,这不起作用,因为“HS4”和“HS4”之间没有转换字典,因此您只能在非 HS4 的行上使用apply

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

相关问题 在 R 中,如何在使用列值的每个 dataframe 行上应用 function? - In R, how to apply a function on each dataframe row that uses a column value? 如何将 function 应用于 R 的 dataframe 中的每一列 - how to apply function to each column in dataframe of R 如何为R中的数据帧中的每一行运行一个函数? - How to run a function for each row in a dataframe in R? 如何索引列表的第一个元素,并将其应用于 R 中的 dataframe 的每一行? - How to index the first element of a list, and apply it to each row of a dataframe in R? 如何将函数应用于每一行并返回R中的行? - How to apply a function to each row and return the row in R? R将函数应用于数据框的每一行,将结果存储在同一数据框的新列中 - R apply function to each row of dataframe, store result in new column of same dataframe 使用Apply函数取消列出数据框中的每一行 - Delist each row in a dataframe using apply function 对 dataframe 的每一行迭代应用优化 function - Apply optim function on iteratively each row of dataframe 如何将 function 应用于数据集的行并获取 R 中每一行的结果 - How to apply a function to a rows of a dataset and get the result for each row in R 在R中的数据框的每个元素上应用带有参数的函数 - Apply function with parameters on each element of a dataframe in R
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM