R:我如何在data.frame的行上使用apply并获取$ column_name?

时间:2022-04-18 04:49:26

I'm trying to access $a using the following example:

我正在尝试使用以下示例访问$ a:

df<-data.frame(a=c("x","x","y","y"),b=c(1,2,3,4))

> df
  a b
1 x 1
2 x 2
3 y 3
4 y 4

test_fun <- function (data.frame_in) {
    print (data.frame_in[1])
    }

I can now access $a if I use an index for the first column:

如果我使用第一列的索引,我现在可以访问$ a:

apply(df, 1, test_fun)

apply(df,1,test_fun)

  a 
"x" 
  a 
"x" 
  a 
"y" 
  a 
"y" 
[1] "x" "x" "y" "y"

But I cannot access column $a with the $ notation: error: "$ operator is invalid for atomic vectors"

但我无法使用$表示法访问列$ a:错误:“$运算符对原子向量无效”

test_fun_2 <- function (data.frame_in) {
    print (data.frame_in$a)
    }

>apply(df, 1, test_fun_2)
Error in data.frame_in$a : $ operator is invalid for atomic vectors

Is this not possible?

这不可能吗?

3 个解决方案

#1


19  

You could use adply from the plyr package instead:

您可以使用plyr包中的adply代替:

library(plyr)
adply(df, 1, function (data.frame_in) print(data.frame_in$a))

#2


10  

because data.frame.in is not a data.frame:

因为data.frame.in不是data.frame:

apply(df, 1, function(v){print(class(v))})

but you can access the named elements with:

但您可以使用以下命令访问命名元素:

test_fun_2 <- function (data.frame_in) {
+     print (data.frame_in['a'])}

#3


5  

Because apply changes the data type in your function:

因为apply会更改函数中的数据类型:

> apply(df, 1, class)
[1] "character" "character" "character" "character"

> apply(df, 1, colnames)
NULL

Since there are no column names, you can't reference the values with the $ operator.

由于没有列名,因此无法使用$运算符引用这些值。

From the apply documentation:

从申请文件:

If X is not an array but has a dimension attribute, apply attempts to coerce it to an array via as.matrix if it is two-dimensional (e.g., data frames) or via as.array.

如果X不是数组但具有维度属性,则应用尝试通过as.matrix将其强制转换为数组(如果它是二维的(例如,数据帧)或通过as.array)。

#1


19  

You could use adply from the plyr package instead:

您可以使用plyr包中的adply代替:

library(plyr)
adply(df, 1, function (data.frame_in) print(data.frame_in$a))

#2


10  

because data.frame.in is not a data.frame:

因为data.frame.in不是data.frame:

apply(df, 1, function(v){print(class(v))})

but you can access the named elements with:

但您可以使用以下命令访问命名元素:

test_fun_2 <- function (data.frame_in) {
+     print (data.frame_in['a'])}

#3


5  

Because apply changes the data type in your function:

因为apply会更改函数中的数据类型:

> apply(df, 1, class)
[1] "character" "character" "character" "character"

> apply(df, 1, colnames)
NULL

Since there are no column names, you can't reference the values with the $ operator.

由于没有列名,因此无法使用$运算符引用这些值。

From the apply documentation:

从申请文件:

If X is not an array but has a dimension attribute, apply attempts to coerce it to an array via as.matrix if it is two-dimensional (e.g., data frames) or via as.array.

如果X不是数组但具有维度属性,则应用尝试通过as.matrix将其强制转换为数组(如果它是二维的(例如,数据帧)或通过as.array)。