基于索引的赋值,在R中应用

基于索引的赋值,在R中应用,r,loops,apply,R,Loops,Apply,我正在清理R中的一些调查数据;根据对问题的回答分配变量1,0。假设我有一个有3个选项的问题;a、 b,c;我有一个包含响应和逻辑变量的数据框架: df <- data.frame(a = rep(0,3), b = rep(0,3), c = rep(0,3), response = I(list(c(1),c(1,2),c(2,3)))) df您可以使用矩阵索引,从?[: 第三种索引形式是通过一列数字矩阵 对于每个维度:然后索引矩阵的每一行选择一个 数组的元素,结果是一个向量。负索引为

我正在清理R中的一些调查数据;根据对问题的回答分配变量1,0。假设我有一个有3个选项的问题;a、 b,c;我有一个包含响应和逻辑变量的数据框架:

df <- data.frame(a = rep(0,3), b = rep(0,3), c = rep(0,3), response = I(list(c(1),c(1,2),c(2,3))))
df您可以使用矩阵索引,从
?[

第三种索引形式是通过一列数字矩阵 对于每个维度:然后索引矩阵的每一行选择一个 数组的元素,结果是一个向量。负索引为 索引矩阵中不允许。允许NA和零值:行 忽略包含零的索引矩阵的 包含NA会在结果中产生NA

#构造一个表示索引的矩阵,其中值应为1
idx也许这有帮助

df[1:3] <- t(sapply(df$response, function(x) as.integer(names(df)[1:3] %in% names(df)[x])))
df
#   a b c response
#1 1 0 0        1
#2 1 1 0     1, 2
#3 0 1 1     2, 3
df[1:3]或者你可以试试这个

library(tidyr)
library(dplyr)
df1=df %>%mutate(Id=row_number()) %>%unnest(response)
df[,1:3]=table(df1$Id,df1$response)


  a b c response
1 1 0 0        1
2 1 1 0     1, 2
3 0 1 1     2, 3

你的预期产出是多少
# construct a matrix representing the index where the value should be one
idx <- with(df, cbind(rep(seq_along(response), lengths(response)), unlist(response)))

idx
#     [,1] [,2]
#[1,]    1    1
#[2,]    2    1
#[3,]    2    2
#[4,]    3    2
#[5,]    3    3

# do the assignment
df[idx] <- 1

df
#  a b c response
#1 1 0 0        1
#2 1 1 0     1, 2
#3 0 1 1     2, 3
df[1:3] <- t(sapply(df$response, function(x) as.integer(names(df)[1:3] %in% names(df)[x])))
df
#   a b c response
#1 1 0 0        1
#2 1 1 0     1, 2
#3 0 1 1     2, 3
library(qdapTools)
df[1:3] <- mtabulate(df$response)
library(tidyr)
library(dplyr)
df1=df %>%mutate(Id=row_number()) %>%unnest(response)
df[,1:3]=table(df1$Id,df1$response)


  a b c response
1 1 0 0        1
2 1 1 0     1, 2
3 0 1 1     2, 3