简体   繁体   English

在数据集点r的列中转换逗号

[英]convert commas in a column of a data set points r

I've imported from excel a dataset. 我已经从excel导入了数据集。 And I have a column 'Height' and I would want to replace the ',' by '.' 我有一列“高度”,我想将“,”替换为“。”。 . I tried with this command but it gives me error. 我尝试使用此命令,但它给了我错误。

apply(apply(DATASET$Height, 2, gsub, patt=",", replace="."), 2, as.numeric)

Thank you very much for your help 非常感谢您的帮助

To recode column 'Height' in data frame 'DATASET': 要重新编码数据框“ DATASET”中的“高度”列:

DATASET$Height <- gsub(",",".",DATASET$Height,fixed=TRUE)

Any errors? 有什么错误吗? If no you can proceed to convert the column to numeric. 如果否,则可以继续将列转换为数字。 Get errors when converting to numeric? 转换为数字时会出错? Perhaps you have still other characters besides "," that prevent R from reading the values as numbers. 也许除了“,”之外还有其他字符阻止R将值读取为数字。 In that case you would need to apply gsub a second time to remove all non-numeric characters. 在这种情况下,您将需要再次应用gsub来删除所有非数字字符。

First, you should check if it is character. 首先,您应该检查它是否是字符。 Then, I would split the strings by the comma, then paste them with a dot: 然后,我将用逗号分隔字符串,然后将它们粘贴到一个点上:

suppose a is what you get with DATASET[["Height"]] 假设您使用DATASET[["Height"]]

a <- c("234,23", "2314,54", "234,65")

then with sapply , you can split and collapse each character element: 然后使用sapply ,可以拆分和折叠每个字符元素:

b <- sapply(a,
  function(string){
    paste0(unlist(strsplit(string, split=",")),collapse=".")
  })

Now, you can replace the DATASET[["Height"]] with b . 现在,您可以将b替换为DATASET[["Height"]]

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM