在R中,我需要比较一个colA(Longitude.x)的前8个字符和第二个colB(X.x)的前8个字符。如果8个字符相同,那么我想将colA(Longitude.x)的值写入新的colC(XCoord)。换句话说,如果colA包含经度值-122.23538,而colB包含X值-122.235873,则我希望colC采取colA -122.23538的值,因为前8个字符(-122.235)匹配。
colA(Longitude.x)和colB(X.x)首次读入R时都为double类型,因此我已使用以下代码将它们转换为字符:
schools_merge$Longitude.x[] <- lapply(schools_merge$Longitude.x[], as.character)
schools_merge$X.x[] <- lapply(schools_merge$X.x[], as.character)
colA和B的类和类型都成为“列表”。
我尝试使用以下代码编写新的colC(XCoord):
schools_merge$XCoord <- if(substr(schools_merge$X.x,1,8) == substr(schools_merge$Longitude.x,1,8)) "yes" else "no"
此代码运行时,它会返回警告-
Warning message:
In if (substr(schools_merge$X.x, 1, 8) == substr(schools_merge$Longitude.x,
: the condition has length > 1 and only the first element will be used
-而不是期望的结果(例如,每个列表中的第二个元素应对colC(XCoord)给出“是”,因为数字-122.23538的字符1-8等于字符-8的字符1-8 -122.235873)。
head(schools_merge$XCoord)
head(schools_merge$Longitude.x)
head(schools_merge$X.x)
> head(schools_merge$XCoord)
[1] "no" "no" "no" "no" "no" "no"
> head(schools_merge$Longitude.x)
[[1]]
[1] "-120.76288"
[[2]]
[1] "-122.23538"
[[3]]
[1] "-122.19604"
[[4]]
[1] "-122.09222"
[[5]]
[1] "-121.77057"
[[6]]
[1] "-122.21629"
> head(schools_merge$X.x)
[[1]]
[1] "-120.763628"
[[2]]
[1] "-122.235873"
[[3]]
[1] "-122.197942"
[[4]]
[1] "-122.092998"
[[5]]
[1] "-121.770702"
[[6]]
[1] "-122.216899"
我可以想到的可能性是:1)我假设算作一个字符(即“-”和“。”以及所有数字)是不正确的,但是我尝试了几次不同的字符数迭代比较,我仍然得到相同的结果– head()全部为“是”或全部为“否”,或2)我可能需要更改为将列转换为向量而不是字符。任何帮助深表感谢!
谢谢你, 安娜
作为对以下评论的回应,以下是数据和脚本的子集的链接:https://sfsu.box.com/s/043n3mxrj4i4mwaefykugjc16yr8mchp
答案 0 :(得分:0)
也许您可以在下面尝试以下代码:
if(substr(schools_merge$X.x,1,8) == substr(schools_merge$Longitude.x,1,8)){
schools_merge$XCoord = "yes"}else{
schools_merge$XCoord = "no"}