【发布时间】:2016-08-31 09:28:28
【问题描述】:
我想替换 URL 中的特定字符串 所以我会为每个“工作”获得一个数据框的链接列。看起来 我的循环有问题。我该如何解决 这个问题?
dat <- read.table(text = " Index job age
44 DBA 0
55 SAS 0
66 CLOUD 0
77 AJAX 0
88 C 1
99 FULLSTACK 1 ", header = TRUE)
dat1<-as.list(dat[[2]])
url = "'as/DD/p=DD"
test <-gsub('DD',dat1[[1]],url,ignore.case = T) # checking the gsub result manually
test
#[1] "'as/DBA/p=DBA" #this is correct
#Now inside a loop
s<- for (i in 1:length(dat1)){
test <-gsub('DD',dat1[[1]],url,ignore.case = T)
}
s
> s
NULL
为什么我得到“Null”而不是以下期望的结果:
as/DBA/p=DBA
as/SAS/p=SAS
as/CLOUD/p=CLOUD
as/AJAX/p=AJAX
as/C/p=C
as/FULLSTACK/p=FULLSTACK
【问题讨论】:
-
for在 R 中返回什么你可以尝试s<-lapply(1:length(dat1),function(i){gsub('DD',dat1[[i]],url,ignore.case = T)}) -
或
lapply(dat1, function(i) gsub('DD',i,url,ignore.case = T))。改为sapply获取向量而不是列表 -
我尝试了两个行代码,但我得到了奇怪的结果(这里是第一行示例):"'as/'as/'as/'as/DBA/p=DBA/p='as/DBA /p=DBA/p='as/'as/DBA/p=DBA/p='as/DBA/p=DBA/p='as/'as/'as/DBA/p=DBA/p=' as/DBA/p=DBA/p='as/'as/DBA/p=DBA/p='as/DBA/p=DBA"