是否可以在整个数据帧中进行二进制对数加一 (log2+1)?
Is it possible to do the binary logarithm plus one (log2+1) in an entire dataframe?
这是我的数据:
dat <- mtcars
dat$Brands <- rownames(dat)
dat$Info <- rep("Info", length(rownames(mtcars)))
我发现有很多方法可以对整个数据框进行处理。 mutate
、sapply
等。但是,对于某些特定功能,它不起作用。
最接近的例子是如果你想做 log2+1
.
我已经试过了...
data_log <- dat %>% mutate(across(where(is.numeric), log2+1))
但是它给了我这个错误...
Error: Problem with mutate()
input ..1
.
ℹ ..1 = across(where(is.numeric), log2 + 1)
.
x non-numeric argument to binary operator
Run rlang::last_error()
to see where the error occurred.
你知道有没有办法运行这种功能?
您的方法是正确的,但语法需要更正。这里需要使用lambda或者匿名函数。
使用 dplyr
您可以将 across
用作 -
library(dplyr)
dat <- dat %>% mutate(across(where(is.numeric), ~log2(.) +1))
或以 R 为基数 -
cols <- sapply(dat, is.numeric)
dat[cols] <- lapply(dat[cols], function(x) log2(x) + 1)
我们可以使用data.table
方法。
library(data.table)
cols <- names(which(sapply(dat, is.numeric)))
setDT(dat)[, (cols) := lapply(.SD, function(x) log2(x) + 1), .SDcols = cols]
其实log2
可以直接在数值数据框上执行,所以你可以试试下面的代码
idx <- sapply(dat, is.numeric)
dat[idx] <- log2(dat[idx])+1
这是我的数据:
dat <- mtcars
dat$Brands <- rownames(dat)
dat$Info <- rep("Info", length(rownames(mtcars)))
我发现有很多方法可以对整个数据框进行处理。 mutate
、sapply
等。但是,对于某些特定功能,它不起作用。
最接近的例子是如果你想做 log2+1
.
我已经试过了...
data_log <- dat %>% mutate(across(where(is.numeric), log2+1))
但是它给了我这个错误...
Error: Problem with
mutate()
input..1
. ℹ..1 = across(where(is.numeric), log2 + 1)
. x non-numeric argument to binary operator Runrlang::last_error()
to see where the error occurred.
你知道有没有办法运行这种功能?
您的方法是正确的,但语法需要更正。这里需要使用lambda或者匿名函数。
使用 dplyr
您可以将 across
用作 -
library(dplyr)
dat <- dat %>% mutate(across(where(is.numeric), ~log2(.) +1))
或以 R 为基数 -
cols <- sapply(dat, is.numeric)
dat[cols] <- lapply(dat[cols], function(x) log2(x) + 1)
我们可以使用data.table
方法。
library(data.table)
cols <- names(which(sapply(dat, is.numeric)))
setDT(dat)[, (cols) := lapply(.SD, function(x) log2(x) + 1), .SDcols = cols]
其实log2
可以直接在数值数据框上执行,所以你可以试试下面的代码
idx <- sapply(dat, is.numeric)
dat[idx] <- log2(dat[idx])+1