我有以下的功能,我能复制成片的代码,但它并没有在数据帧直接运行。我现在需要简单地对有轻微变化的数据帧运行它,但不能找出正确的语法这样做。
功能很简单: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
))
似乎在第一列失去尾随零,但这个工程考虑您的示例数据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()
还有您可以使用几种方法:
daf[, 2:5] <- lapply(daf[, 2:5], fu)
#library(dplyr)
mutate_at(daf, vars(data_2017:general), fu)
#library(data.table)
dat <- data.table(daf)
dat[,
(colnames(dat)[-1]) := lapply(.SD, fu),
.SDcols = -1
]
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)
)
fu <- function(x) ifelse(x>0, paste0("+", x), x)
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
来电显示输出