簡體   English   中英

根據向量的第一個字符重新編碼R中的變量

[英]Recode variable in R based on first characters of vector

我有一個數據框架,看起來像這樣:

codes <- c('TFAA1', 'TFAA2', 'TFAA3', 'TFAA4', 'TFAB1', 'TFAB2', 'TFAB3', 'TFAB4')
scores <- c(4,3,2,2,4,5,1,2)
example <- data.frame(codes, scores)

我想創建一個名為code_group的新列,以TFAA開頭的所有內容都稱為“ Group1”,以TFAB開頭的所有內容都稱為“ Group2”。

一直在使用car包中的recode函數和grepl函數,但是我失敗了。 到目前為止,這是我的嘗試。

recode <- (codes, "%in% TFAA='Group1'; %in% TFAB='Group2'")

使用dplyrstringr您可以完成此操作:

library(dplyr)
library(stringr)
example %>% 
  mutate(code_group = case_when(str_detect(codes, "^TFAA") ~ "Group1",
                              str_detect(codes, "^TFAB") ~ "Group2"))

case_when使您可以使用多個if-then案例。 str_detect使您可以很好地檢測在字符串中尋找的模式。

example$code_group <- ifelse(startsWith(codes, 'TFAA'), 'Group 1', 
                      ifelse(startsWith(codes, 'TFAB'), 'Group 2',
                             NA))

我們可以使用substr提取前四個字符,將其轉換為factor並將labels指定為我們想要的labels

example$code_group <-  with(example,  as.character(factor(substr(codes, 1, 4), 
              levels = c('TFAA', 'TFAB'), labels = c('Group1', 'Group2'))))

我們可以使用split<-

example$group <- NA
split(example$group,substr(example$codes,1,4)) <- paste0("Group",1:2)
example
#   codes scores  group
# 1 TFAA1      4 Group1
# 2 TFAA2      3 Group1
# 3 TFAA3      2 Group1
# 4 TFAA4      2 Group1
# 5 TFAB1      4 Group2
# 6 TFAB2      5 Group2
# 7 TFAB3      1 Group2
# 8 TFAB4      2 Group2

或者我們可以將因子用於相同的輸出(3個變體):

example$group <- paste0("Group",factor(substr(example$codes,1,4),,1:2))
example$group <- paste0("Group",as.numeric(factor(substr(example$codes,1,4))))
example$group <- factor(substr(example$codes,1,4),,paste0("Group",1:2))

在最后一種情況下,您將獲得一個因子列,在所有其他情況下,您將獲得一個字符列。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM