在 R 中的数据框上使用 apply() 函数时如何保留非数字列?

问题描述 投票:0回答:1

我有一个数据框,其中一列包含非数字值。我需要在数字列上应用函数并创建新的数据框,但我想在这个新数据框中保留非数字值的列。

#Data frame (exemple)
df <- data.frame(col1 = c(1:5), col2 = c(6:10), col3 = c("x","y","z","w","x"))

#Function (exemple)
sum1 <- function(x){x + 1}

df_aplly <- as.data.frame(apply(df, MARGIN = 2, FUN = sum1))

此示例返回错误:

Error in x + 1 : non-numeric argument to binary operator

我尝试仅应用于数字列:

#Function (exemple)
sum1 <- function(x){x + 1}

df_aplly <- as.data.frame(apply(df[1:2], MARGIN = 2, FUN = sum1))

> df_aplly
  col1 col2
1    2    7
2    3    8
3    4    9
4    5   10
5    6   11

它可以工作,但返回一个只有 2 列的新数据框,但我需要在这个新数据框中保留非数字列。

有没有办法只使用“apply()”函数来做到这一点?

#data frame i need:
> df_aplly
  col1 col2 df$col3
1    2    7       x
2    3    8       y
3    4    9       z
4    5   10       w
5    6   11       x


r character apply bind numeric
1个回答
0
投票

您可以使用 dplyr

> df %>% 
    mutate_if(is.numeric, sum1)
  col1 col2 col3
1    2    7    x
2    3    8    y
3    4    9    z
4    5   10    w
5    6   11    x
© www.soinside.com 2019 - 2024. All rights reserved.