如何定义和运行在数据帧的功能?

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

我有以下的功能,我能复制成片的代码,但它并没有在数据帧直接运行。我现在需要简单地对有轻微变化的数据帧运行它,但不能找出正确的语法这样做。

功能很简单:function(x) ifelse(x>0, paste0("+", x), x)

而变化是,我想在除第一列每列运行。因此,第一个栏后,这个功能应该在重复数据帧在所有细胞,并在前面加上一个+标志的任何正值。

我想运行在数据帧df修改的功能。有没有办法做到这一点在线?

样本数据一起玩:

structure(list(data_2018 = c(3.2, 3, 3.2), data_2017 = c(2.825, 
0, -0.425), pilot = c(0.51578947368421, -0.0526315789473699, 
0.41052631578947), all = c(0.42222222222222, -0.18518518518519, 
0.27407407407407), general = c(0.40833333333333, -0.0833333333333299, 
0.36666666666667)), class = "data.frame", row.names = c(NA, -3L
))
r
2个回答
1
投票

似乎在第一列失去尾随零,但这个工程考虑您的示例数据df时:

df2 <- as.data.frame(apply(df, 2, function(x) if_else(substr(as.character(x), 1, 1) == "-" | as.character(x) == "0",
                                                  as.character(x),
                                                  paste0("+", as.character(x)))))

我采取了不同的方法 - 我看了减号或零为字符,然后从那里添加+。

UPDATE - 下面dplyr简化代码

library(dplyr)
df2 <- df %>%
  mutate_all(as.character) %>% 
  apply(2, function(x) if_else(substr(x, 1, 1) == "-" | x == "0",
                           x,
                           paste0("+", x))) %>% 
  as.data.frame()

0
投票

还有您可以使用几种方法:


base

daf[, 2:5] <- lapply(daf[, 2:5], fu)

dplyr

#library(dplyr)

mutate_at(daf, vars(data_2017:general), fu)

data.table

#library(data.table)

dat <- data.table(daf)

dat[, 
    (colnames(dat)[-1]) := lapply(.SD, fu), 
    .SDcols = -1
    ]

data

daf <- structure(
  list(data_2018 = c(3.2, 3, 3.2), 
       data_2017 = c(2.825, 0, -0.425), 
       pilot = c(0.51578947368421, -0.0526315789473699, 0.41052631578947), 
       all = c(0.42222222222222, -0.18518518518519, 0.27407407407407), 
       general = c(0.40833333333333, -0.0833333333333299, 0.36666666666667)
  ), 
  class = "data.frame", row.names = c(NA, -3L)
)

function

fu <- function(x) ifelse(x>0, paste0("+", x), x)

output

  data_2018 data_2017               pilot               all             general
1       3.2    +2.825   +0.51578947368421 +0.42222222222222   +0.40833333333333
2       3.0         0 -0.0526315789473699 -0.18518518518519 -0.0833333333333299
3       3.2    -0.425   +0.41052631578947 +0.27407407407407   +0.36666666666667

只为lapply来电显示输出


© www.soinside.com 2019 - 2024. All rights reserved.