R使用purrr :: map在数据框列表中的选定列上应用函数

问题描述 投票:1回答:1

我有一个数据帧列表,其中一些列需要指定其正确的编码。所以,我创建了一个设置正确编码的函数,我想将这个新函数应用于我的数据帧列表中的特定列。我怎么能用purrr:map做到这一点?我很新。


虚拟的例子

# Set slovak characters
Sys.setlocale(category = "LC_ALL", locale = "Slovak")


# Make a function    
setEncoding<- function(x, ...) {
    Encoding(x)<-"UTF-8"  # set correct encoding on the vector
    x                     # print the output
}

# Create dummy data with wrong encoding
df1<-data.frame(name = "Ľubietovský Vepor",
                psb = "S CHKO PoÄľana",
                numb = 1)

df2<-data.frame(name = "Goliašová",
                psb = "S TANAP",
                numb = 2)

list1<-list(df1, df2)

My function seems working if applied on vector string:

>setEncoding(c("Ľubietovský Vepor", "Goliašová" ))
[1] "Ľubietovský Vepor" "Goliašová"  

# How to apply the whatever function (here setEncoding) on the selected columns from a dataframe list?? 

list1 %>%
  map(setEncoding[c("name", "psb")]) # How to fix this?

我希望获得(正确编码列namepsb):

> ls
[[1]]
         name            psb numb
1 Ľubietovský Vepor S CHKO Poľana    1

[[2]]
         name     psb numb
1 Goliášová S TANAP    2
r dictionary purrr
1个回答
1
投票

我不知道你想要的结果的编码细节,但我可以回答有关使用purrr的问题。您可以使用map_if仅将函数应用于character向量(因为Encoding()需要character输入)。您的示例数据框也包含因子而不是字符串。

library(purrr)
df1<-data.frame(name = "Ľubietovský Vepor",
                psb = "S CHKO PoÄľana",
                numb = 1, stringsAsFactors = FALSE)

df2<-data.frame(name = "Goliašová",
                psb = "S TANAP",
                numb = 2, stringsAsFactors = FALSE)

list1 <- list(df1, df2) #using ls conflicts with ls() function

list1 %>% 
  map_if(is.character, setEncoding) #this only maps on 'name' and 'pbs'
© www.soinside.com 2019 - 2024. All rights reserved.