如何使用R

时间:2018-12-14 11:22:59

标签: r

df1中与数据帧lookup_df中的lab_pt相匹配的级别,我想替换为lookup_df第二栏中的相应级别(此处为lab_en)。但我想保留其余的一切。 非常感谢!

--

主数据框

df1 <- data.frame(
            num_var = sample(200, 15),
            col1 = rep(c("onda","estrela","rato","caneta","ceu"), 3),
            col2 = rep(c("muro","gato","pa","rato","ceu"), 3),
            col3 = rep(c("surf","onda","dente","onda","sei"), 3),
            col3 = rep(c("onda","casa",NA,"nao","net"), 3))

停放数据帧

lookup_df <- data.frame(
            lab_pt = c("onda","estrela","rato","caneta","ceu"),
            lab_en = c("wave","star","rat","pen","sky"))

我已经在下面尝试过了。它可以完成工作,但是不匹配的信息会转换为NA,这是我不想要的。

rownames(lookup_df) <- lookup_df$lab_pt
apply(df1[,2:ncol(df1)], 2, function(x) lookup_df[as.character(x),]$lab_en)

这里的帖子非常相似,但是在这种情况下,所有级别都是可匹配的,与此不同。非常感谢! Replace values in a dataframe based on lookup table

5 个答案:

答案 0 :(得分:1)

我认为应该使用data.table软件包来做到这一点。它会重新排序ID,这是问题吗?

# added seed
# changed col3 to col4
set.seed(1)
df1 <- data.frame(
  num_var = sample(200, 15),
  col1 = rep(c("onda","estrela","rato","caneta","ceu"), 3),
  col2 = rep(c("muro","gato","pa","rato","ceu"), 3),
  col3 = rep(c("surf","onda","dente","onda","sei"), 3),
  col4 = rep(c("onda","casa",NA,"nao","net"), 3))

lookup_df <- data.frame(
  lab_pt = c("onda","estrela","rato","caneta","ceu"),
  lab_en = c("wave","star","rat","pen","sky"))

# data.table solution
library(data.table)

# change from wide to long, to make merge easier
dt <- melt(as.data.table(df1), id.vars="num_var")

# merge in the new values to original data
dt2 <- merge(dt, lookup_df, by.x="value", by.y="lab_pt",
             all.x=TRUE)

# if its missing, replace with original value
dt2[is.na(lab_en), lab_en := value]

# convert back from long to wide
dt3 <- dcast(dt2[, .(num_var, variable, lab_en)], num_var~variable,
            value.var="lab_en")

# back to data.frame
output <- as.data.frame(dt3)

每当在表之间进行合并时,通常使用长格式数据(组列和值列在其中)会更好。这意味着您无需多次运行同一操作(合并)。

答案 1 :(得分:1)

我认为这可能会对您有所帮助,尽管会创建一个新列,但可以完成工作

df1$new <- lookup_df[match(df1$col1, lookup_df$lab_pt),2]

答案 2 :(得分:1)

您可以执行以下操作:

Star

答案 3 :(得分:1)

这是使用dplyr软件包的解决方案。 注意参数stringAsFactor=F将单词保留为字符串。

   df1 <- data.frame(
      num_var = sample(200, 15),
      col1 = rep(c("onda","estrela","rato","caneta","ceu"), 3),
      col2 = rep(c("muro","gato","pa","rato","ceu"), 3),
      col3 = rep(c("surf","onda","dente","onda","sei"), 3),
      col3 = rep(c("onda","casa",NA,"nao","net"), 3), stringsAsFactors = F)

    lookup_df <- data.frame(
      lab_pt = c("onda","estrela","rato","caneta","ceu"),
      lab_en = c("wave","star","rat","pen","sky"), stringsAsFactors = F)


    library(dplyr)

    df1 %>% mutate(col1=replace(col1, col1 %in% lookup_df$lab_pt, lookup_df$lab_en)) %>% 
      mutate(col2=replace(col2, col2 %in% lookup_df$lab_pt, lookup_df$lab_en)) %>% 
      mutate(col3=replace(col3, col3 %in% lookup_df$lab_pt, lookup_df$lab_en)) %>%
      mutate(col3.1=replace(col3.1, col3.1 %in% lookup_df$lab_pt, lookup_df$lab_en))

我承认为数据帧的每一列使用一行很繁琐。无法找到一种方法一次对所有列进行处理。

   num_var col1 col2  col3 col3.1
1        6 wave muro  surf   wave
2       84 star gato  wave   casa
3      146  rat   pa dente   <NA>
4      133  pen wave  star    nao
5       47  sky star   sei    net
6      116 wave muro  surf   star
7       81 star gato   rat   casa
8      118  rat   pa dente   <NA>
9      186  pen  rat   pen    nao
10     161  sky  pen   sei    net
11     135 wave muro  surf    rat
12      31 star gato   sky   casa
13     174  rat   pa dente   <NA>
14     187  pen  sky  wave    nao
15     178  sky wave   sei    net

答案 4 :(得分:0)

# Fake dataframe
df1 <- tibble(
        num_var = sample(200, 15),
        col1 = rep(c("onda","estrela","rato","caneta","ceu"), 3),
        col2 = rep(c("muro","gato","pa","rato","ceu"), 3),
        col3 = rep(c("surf","onda","dente","onda","sei"), 3),
        col4 = rep(c("onda","casa",NA,"nao","net"), 3))

# Lookup dictionary dataframe
lookup_dat <- tibble(
        lab_pt = c("onda","estrela","rato","caneta","ceu"),
        lab_en = c("wave","star","rat","pen","sky")) 

#******************************************************************
#
# Translation by replacement of lookup dictionary 
# Developed to generate Rmd report with labels of plots in different languages
replace_level <- function(df, lookup_df, col_langu_in, col_langu_out){
        library(data.table)
        # function to replace levels in the df given a reference list in 
        # another df when level match it replace with the correspondent 
        #level in the same row name but in other column.
        # !!!! Variables col_langu need to be quoted 
           # 1) Below it creates a dictionary style with the reference df (2cols)
         lookup_vec <- setNames(as.character(lookup_df[[col_langu_out]]), 
                               lookup_df[[col_langu_in]])
           # 2) iterating over main df col names
         for (i in names(df)) { # select cols?: names(df)[sapply(df, is.factor)]
           # 3) return index of levels from df levels matching with those from 
                 # the dictionary type to replace (for each cols of df i)
                 if(is.character(df[[i]])){df[i] <- as.factor(df[[i]])}
                 # Changing from character to factor before the translation
                 index_match <- which(levels(df[[i]]) %in% 
                                              names(lookup_vec))
           # 4) replacing matchable levels based on the index on step 3).
                 # with the reference to translate
                 levels(df[[i]])[index_match] <- 
                         lookup_vec[levels(df[[i]])[index_match]]}
         return(df)}

# test here
replace_level(df1, lookup_dat, "lab_pt", "lab_en")