【问题标题】:using utf8toInt on a dataframe在数据帧上使用 utf8toInt
【发布时间】:2018-10-05 14:08:27
【问题描述】:

对 R 来说非常陌生。我正在尝试对数据框使用 utf8toInt。
我想扫描数据帧中的 Int 值 101 (e) 并将其替换为 69 (E)。

我的问题是如何遍历数据框中的每个值并执行 utf8ToInt 函数。 {`

在这里构建 UTF 函数

a b c

df = data.frame(a,b,c)

df
a b c
1红蓝白
2蓝黄黑
3黄红红
4黑色粉色蓝色

尝试针对单个值运行时

utf8ToInt(df[1]) utf8ToInt(df[1]) 中的错误:参数必须是长度为 1 的字符向量

'}

【问题讨论】:

  • 试试lapply(df[[1]],utf8ToInt)
  • > lapply(df[[1]],utf8ToInt) FUN(X[[i]], ...) 中的错误:参数必须是长度为 1 的字符向量 >

标签: r


【解决方案1】:

永远不要使用c 作为变量名,因为c() 也是一个函数。

a <- c("red", "blue", "yellow", "black");b<- c("blue", "yellow", "red", "pink");c1<- c("white", "black", "red", "blue")

注意stringsAsFactors = F 部分。

df = data.frame(a,b,c1,stringsAsFactors = F)

lapply(df[[1]],utf8ToInt)

结果

# [[1]]
# [1] 114 101 100
# 
# [[2]]
# [1]  98 108 117 101
# 
# [[3]]
# [1] 121 101 108 108 111 119
# 
# [[4]]
# [1]  98 108  97  99 107

旁注:它不起作用的原因是因为factor 变量在内部被编码为整数值:

utf8ToInt("red")  #works
utf8ToInt(factor("red")) #does not work
utf8ToInt(1) #does not work

要转换整个数据集,您可以将其转换为 matrix

lapply(as.matrix(df),utf8ToInt)

阅读您的问题:如果您想用“E”替换“e”,为什么不简单地使用正则表达式?

df

       a      b    c1
1    red   blue white
2   blue yellow black
3 yellow    red   red
4  black   pink  blue

然后使用:

df[] <- sapply(as.matrix(df),gsub,pattern="e",replacement="E")

       a      b    c1
1    rEd   bluE whitE
2   bluE yEllow black
3 yEllow    rEd   rEd
4  black   pink  bluE

【讨论】:

  • 我仅以颜色数据框为例。我对 utf8toInt 的工作原理特别感兴趣。用于将 E 更改为 e 的方法只是一个练习。感谢您的帮助。
猜你喜欢
  • 2022-01-15
  • 2018-05-06
  • 2023-03-03
  • 2019-04-18
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2018-02-23
  • 2021-09-01
相关资源
最近更新 更多