我有一个数据帧列表,其中某些列需要指定其正确编码。因此,我创建了一个函数来设置正确的编码,并且我想将此新函数应用于我的数据框列表中的特定列。如何使用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?
我希望获得的内容(对列name
,psb
的正确编码):
> ls
[[1]]
name psb numb
1 Ľubietovský Vepor S CHKO Poľana 1
[[2]]
name psb numb
1 Goliášová S TANAP 2
答案 0 :(得分: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'