在具有整数和字符变量的数据帧上逐行应用 FUN [英] Apply FUN row-wise on data frame with integer and character variables

查看:16
本文介绍了在具有整数和字符变量的数据帧上逐行应用 FUN的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

一个完全基本的问题 - 如果它是重复的,请原谅我.

A completely basic question - and forgive me if it is a duplicate.

set.seed(1)
df <- 
  data.frame(id=c('a', 'a', 'b', 'b', 'a'),
             a=sample(1:10, size=5, replace=T),
             b=sample(1:10, size=5, replace=T),
             c=sample(1:10, size=5, replace=T)) 

那么,

> df
  id  a  b c
1  a  3  9 3
2  a  4 10 2
3  b  6  7 7
4  b 10  7 4
5  a  3  1 8

要返回具有最大值的列名(a、b 或 c),如果这是在 id 变量中取第二大,我使用下面的函数.

To return the column name (a, b or c) with the largest value, and if this is in the id variable take the second highest, I use the below function.

FUN <- function(r) {
  top <- names(r[,c('a', 'b', 'c')])[order(r[,c('a', 'b', 'c')], decreasing=T)]
  ifelse(top[1] == r[['id']], top[2], top[1])
}

我能做到:

FUN(df[1,]) #[1] "b"

对于所有行:

res <- NULL
for(i in 1:nrow(df)) {
res <- c(res, FUN(df[i,]))  
}

得到

> res
[1] "b" "b" "c" "a" "c"

但是我如何应用这个?例如.这不起作用:

But how can I apply this ? E.g. this is not working:

apply(df, 1, FUN)

我怀疑问题在于 FUN 假设一个 1 行数据框(而不是像(第一行)这样的命名字符向量)

I suspect the trouble is that FUN assumes a 1-row data frame (and not a named vector of characters like (first row))

 id   a   b   c 
"a" "3" "9" "c"

申请?:

如果 X 不是数组而是具有非空 dim 值的类的对象(例如数据框),则尝试通过 as.matrix 将其强制转换为二维数组(例如, 数据框) 或通过 as.array.

If X is not an array but an object of a class with a non-null dim value (such as a data frame), apply attempts to coerce it to an array via as.matrix if it is two-dimensional (e.g., a data frame) or via as.array.

推荐答案

如果你必须使用你的函数,你可以这样做,

If you must use your function, you can do,

sapply(split(df, 1:nrow(df)), f1)
#  1   2   3   4   5 
#"b" "b" "c" "a" "c" 

注意 我将您的 FUN 重命名为 f1 因为 FUN 被 R 中的各种函数使用,以便定义函数的参数

NOTE I renamed your FUN to f1 since FUN is used by various functions in R so as to define the argument of function

这篇关于在具有整数和字符变量的数据帧上逐行应用 FUN的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆