英文:
How can I convert a data table to its logarithm (+1, base 2) form in R while ignoring non-numeric values?
问题
我试图将数据表的值转换为其 log(a)+1(以2为底)的形式,并创建一个经过转换的数据表在R中。但数据表的前两列不是数字,因此我需要将它们从计算中排除,否则会出现错误。我知道如何分别执行这两个操作,但当我将它们结合起来时,会出现错误,指出前两列不是数值。
以下是我的代码:
logDT = log(DT, 2) + 1[, -c(1, 2)]
我知道我可以创建一个中间数据表,先排除前两列,然后生成对数表,但我确实需要将前两列包含在对数表中,所以我宁愿找到一种方法让我的原始代码工作。
以下是一个示例代码(这个代码与我的实际代码唯一的区别是我的实际代码有两列非数值列,而这个代码只有一列):
DT = data.table(x=c("b","b","b","a","a"),v=rnorm(5))
希望这可以帮助你解决问题。
英文:
I'm trying to convert the values of a data table to its log(a)+1 (base 2) into a transformed data table in R. But the first two columns of the data tables are not numbers so I need to exclude them from the calculation or I will get an error. I do know how to do these two operations individually but when I combine them, I get an error saying the first two columns are not numerical values.
Here is my code:
logDT = log(DT, 2) + 1[, -c(1, 2)]
I am aware that I can just create an intermediary data table that excludes the columns first and then produce the log table, but I do need the first two columns in there in the log table so I'd rather just find a way to make my original code work.
Here's an example code (the only real difference between this and my actual code is that my actual code has two non-numerical columns while this code has one):
DT = data.table(x=c("b","b","b","a","a"),v=rnorm(5))
<pre> x v
1: b -0.4149946
2: b -0.3942900
3: b -0.0593134
4: a 1.1000254
5: a 0.7631757</pre>
答案1
得分: 0
使用which(sapply())
获取数字列的索引,然后使用data.table::set()
进行转换:
库(data.table)
对于 (j 在 which(sapply(logDT, is.numeric))) {
设置(logDT, j = j, value = log(logDT[[j]], 2) + 1)
}
logDT
x v1 v2
1: b 0.148809 -0.2669889
2: b NaN 1.2980794
3: b 1.827952 -1.0789923
4: a -1.416422 NaN
5: a 1.192227 1.1442347
示例数据:
设置种子(13)
DT <- 数据表(x = c("b","b","b","a","a"), v1 = rnorm(5), v2 = rnorm(5))
英文:
Use which(sapply())
to get indices of numeric columns, then data.table::set()
to transform:
library(data.table)
logDT <- DT
for (j in which(sapply(logDT, is.numeric))) {
set(logDT, j = j, value = log(logDT[[j]], 2) + 1)
}
logDT
x v1 v2
1: b 0.148809 -0.2669889
2: b NaN 1.2980794
3: b 1.827952 -1.0789923
4: a -1.416422 NaN
5: a 1.192227 1.1442347
Example data:
set.seed(13)
DT <- data.table(x = c("b","b","b","a","a"), v1 = rnorm(5), v2 = rnorm(5))
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论