我有一个整数数据帧,我想将其转换为位,然后将每个结果位序列拆分成单独的列。我想我可以将我的位转换为字符串,然后将字符串拆分为空格。但是,我的方法不起作用。
我创建了我的数据框:
r1 <- c(24,25,27)
r2 <- c(98,102,4)
model.data <- as.data.frame(rbind(r1,r2))
然后我将int转换为位:
model.data[] <- lapply(model.data, function(x) {
if(!is.na(x)) as.character(paste(intToBits(x), collapse = " ")) else x
})
然而,这是我遇到第一个问题的地方。我的数据框的第二行现在似乎与第一行具有相同的值:
model.data $ V1
[1]&#34; 00 00 00 01 01 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 01 01 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00&#34;
[2]&#34; 00 00 00 01 01 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 01 01 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00&#34;
情况并非如此,因为原始数据框中的值不同。这里所有列的情况都是相同的(V2,V3)。
我的第二个问题是我无法拆分列。我尝试这种方法:
for(i in names(model.data)) {
a.split <- strsplit(model.data[[i]], split = " ")
cbind(model.data,a.split)
}
但它什么也没做。
你可以帮我弄清楚我做错了什么吗?谢谢!答案 0 :(得分:3)
使用功能&#34;分开&#34;来自tidyr包
library(tidyr)
# Your data
r1 <- c(24,25,27)
r2 <- c(98,102,4)
# Concatenate r1 and r2
r3 <- c(r1,r2)
# Create a dataframe
model.data <- as.data.frame(r3)
# Check type of r3
class(model.data$r3)
# Transform with "intToBits" function
model.data[] <- lapply(model.data, function(x) {
if(!is.na(x)) as.character(paste(intToBits(x), collapse = " ")) else x
})
nb = length(unlist(strsplit(model.data$r3[1]," ")))
# Transform into character
model.data$r3 <- as.character(model.data$r3)
# Use "separate" function from tidyr, generating nb variable
model.data %>% separate(r3, into = paste0("V",seq(1, nb, by = 1)), sep = " ")
答案 1 :(得分:2)
您需要使用apply
在行和列上ifelse
。有趣的是,使用lapply
似乎不起作用。这是apply
解决方案的示例:
r1 <- c(24,25,27)
r2 <- c(98,102,4)
model.data <- as.data.frame(rbind(r1,r2))
model.data[] <- as.data.frame(apply(model.data, c(1,2), function(x) ifelse(!is.na(x), as.character(paste(intToBits(x), collapse = " ")), x)), stringsAsFactors = FALSE)
> model.data
V1
r1 00 00 00 01 01 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00
r2 00 01 00 00 00 01 01 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00
V2
r1 01 00 00 01 01 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00
r2 00 01 01 00 00 01 01 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00
V3
r1 01 01 00 01 01 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00
r2 00 00 01 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00
编辑:
要创建每个变量一位的新数据,首先lapply
strsplit
,给出一个嵌套列表作为输出,然后使用嵌套do.call
来{{1} }子列表,然后cbind
结果:
rbind