在`data.table`中合并数值

huangapple go评论101阅读模式
英文:

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:

  1. dt <- data.table(q32_1 = c(1, 2, 3, 4, 5),
  2. q32_2 = c(1, 2, 3, 4, 5),
  3. q32_3 = c(1, 2, 3, 4, 5),
  4. q22_1 = c(1, 2, 3, 4),
  5. q22_2 = c(1, 2, 3, 4),
  6. 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:

  1. cols <- grep("^q22", names(dt), value = TRUE)
  2. dt[, (cols) := lapply(.SD, function(i) ifelse(i %in% 1:2, 1, i)), .SDcols = cols ]
  3. dt
  4. # q32_1 q32_2 q32_3 q22_1 q22_2 q22_3
  5. # 1: 1 1 1 1 1 1
  6. # 2: 1 1 1 1 1 1
  7. # 3: 3 3 3 3 3 3
  8. # 4: 4 4 4 4 4 4
  9. # 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:

  1. cols &lt;- grep(&quot;^q22&quot;, names(dt), value = TRUE)
  2. dt[, (cols) := lapply(.SD, function(i) ifelse(i %in% 1:2, 1, i)), .SDcols = cols ]
  3. dt
  4. # q32_1 q32_2 q32_3 q22_1 q22_2 q22_3
  5. # 1: 1 1 1 1 1 1
  6. # 2: 2 2 2 1 1 1
  7. # 3: 3 3 3 3 3 3
  8. # 4: 4 4 4 4 4 4
  9. # 5: 5 5 5 1 1 1

答案2

得分: 2

使用 data.tableset() 函数:

  1. for (col in names(dt)) {
  2. if (col %like% "^q22_[1-3]$") set(dt, which(dt[[col]] == 2), col, value = 1)
  3. }
英文:

Using data.table's set():

  1. for (col in names(dt)) {
  2. if (col %like% &quot;^q22_[1-3]$&quot;) set(dt, which(dt[[col]] == 2), col, value = 1)
  3. }

答案3

得分: -1

请尝试以下代码:

  1. library(tidyverse)
  2. dt %>% mutate(across(starts_with('q22'), ~ifelse(.x==2,1,.x)))
  3. #output
  4. q32_1 q32_2 q32_3 q22_1 q22_2 q22_3
  5. 1: 1 1 1 1 1 1
  6. 2: 2 2 2 1 1 1
  7. 3: 3 3 3 3 3 3
  8. 4: 4 4 4 4 4 4
  9. 5: 5 5 5 1 1 1
英文:

Please try the below code

  1. library(tidyverse)
  2. dt %&gt;% mutate(across(starts_with(&#39;q22&#39;), ~ifelse(.x==2,1,.x)))
  3. #output
  4. q32_1 q32_2 q32_3 q22_1 q22_2 q22_3
  5. 1: 1 1 1 1 1 1
  6. 2: 2 2 2 1 1 1
  7. 3: 3 3 3 3 3 3
  8. 4: 4 4 4 4 4 4
  9. 5: 5 5 5 1 1 1

huangapple
  • 本文由 发表于 2023年6月26日 19:14:53
  • 转载请务必保留本文链接:https://go.coder-hub.com/76556154.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定