Reputation: 1746
I've a list in this form:
s = c("aa", "bb", "cc", "dd", "ee","xx")
I want to loop over this list till all the elements are consider. Then I want to check if each element is not equal to "blank". If it's not I want to create a variable which is each element of "s" and concatenation of a constant string, say "_file". Finally stack each of these elements.
The code I created is the following. But it's giving me blank.
s = c("aa", "bb", "cc", "dd", "ee","xx")
t<-if(length(s)>0){
for(i in s){
if(length(s)>0){
i2=i*"_file"
}
else{
i2=''
}
i2<-c()
}
}
I tried this as well. But it's running for long.
s = c("aa", "bb", "cc", "dd", "ee","xx")
t<-while(s!=''){
for(i in s){
if(length(s)>0){
i2=i*"_file"
}
else{
i2=''
}
i2<-c()
}
}
Can anyone please help me?
Thanks!
Upvotes: 0
Views: 73
Reputation: 31171
Just the 'very concise one liner'
paste0(Filter(nchar, s), '_file')
Upvotes: 2
Reputation: 887118
Here is an option with sub
sub("^([a-z]+)$", "\\1_file", s)
#[1] "aa_file" "bb_file" "cc_file" "dd_file" "ee_file" "" "xx_file"
s <- c("aa", "bb", "cc", "dd", "ee", "", "xx")
Upvotes: 2
Reputation: 2100
Here's what I would do. I am sure there are even faster solutions...
s <- c("aa", "bb", "cc", "dd", "ee","xx")
s[nchar(s)>0]<-paste0(s,"_file")
That should do the trick
Upvotes: 1
Reputation: 25736
This could be vectorized using nzchar
:
s <- c("aa", "bb", "cc", "dd", "ee", "", "xx")
paste(s[nzchar(s)], "file", sep="_")
# [1] "aa_file" "bb_file" "cc_file" "dd_file" "ee_file" "xx_file"
Upvotes: 3