英文:
Combine values in data.table
问题
我想要将q22(1-3)中的值1和2合并为1,应该如何操作?
英文:
I have a large dataset with different columns that represent questions from a questionnaire:
dt <- data.table(q32_1 = c(1, 2, 3, 4, 5),
q32_2 = c(1, 2, 3, 4, 5),
q32_3 = c(1, 2, 3, 4, 5),
q22_1 = c(1, 2, 3, 4),
q22_2 = c(1, 2, 3, 4),
q22_3 = c(1, 2, 3, 4))
different questions has different levels of options that people could choose when answering the questions.
I want for q22(1-3) combine value 1 and 2 so they both are 1 how can I do so?
答案1
得分: 2
Loop through subset of column names, and change 2s to 1:
cols <- grep("^q22", names(dt), value = TRUE)
dt[, (cols) := lapply(.SD, function(i) ifelse(i %in% 1:2, 1, i)), .SDcols = cols ]
dt
# q32_1 q32_2 q32_3 q22_1 q22_2 q22_3
# 1: 1 1 1 1 1 1
# 2: 1 1 1 1 1 1
# 3: 3 3 3 3 3 3
# 4: 4 4 4 4 4 4
# 5: 5 5 5 1 1 1
(Note: The code provided changes 2s to 1s in columns that start with "q22" and leaves other columns unchanged.)
英文:
Loop through subset of column names, and change 2s to 1:
cols <- grep("^q22", names(dt), value = TRUE)
dt[, (cols) := lapply(.SD, function(i) ifelse(i %in% 1:2, 1, i)), .SDcols = cols ]
dt
# q32_1 q32_2 q32_3 q22_1 q22_2 q22_3
# 1: 1 1 1 1 1 1
# 2: 2 2 2 1 1 1
# 3: 3 3 3 3 3 3
# 4: 4 4 4 4 4 4
# 5: 5 5 5 1 1 1
答案2
得分: 2
使用 data.table
的 set()
函数:
for (col in names(dt)) {
if (col %like% "^q22_[1-3]$") set(dt, which(dt[[col]] == 2), col, value = 1)
}
英文:
Using data.table
's set()
:
for (col in names(dt)) {
if (col %like% "^q22_[1-3]$") set(dt, which(dt[[col]] == 2), col, value = 1)
}
答案3
得分: -1
请尝试以下代码:
library(tidyverse)
dt %>% mutate(across(starts_with('q22'), ~ifelse(.x==2,1,.x)))
#output
q32_1 q32_2 q32_3 q22_1 q22_2 q22_3
1: 1 1 1 1 1 1
2: 2 2 2 1 1 1
3: 3 3 3 3 3 3
4: 4 4 4 4 4 4
5: 5 5 5 1 1 1
英文:
Please try the below code
library(tidyverse)
dt %>% mutate(across(starts_with('q22'), ~ifelse(.x==2,1,.x)))
#output
q32_1 q32_2 q32_3 q22_1 q22_2 q22_3
1: 1 1 1 1 1 1
2: 2 2 2 1 1 1
3: 3 3 3 3 3 3
4: 4 4 4 4 4 4
5: 5 5 5 1 1 1
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论