我有一个列名的dataframe,如下所示:
d=c("Q.40a-some Text", "Q.40b-some Text", "Q.44a-some Text", "Q.44b-some Text" "Q.44c-some Text" "Q.44d-some Text" ,"Q.4a-some Text", "Q.4b-some Text")我想找出以Q.4开头的列,忽略Q.40,Q.44。
例如,识别Q.44或Q.40很容易。我所做的就是使用这个"^Q.44"或"^Q.40“作为函数的输入。但是,如果我在识别Q.4时也这样做的话,这是行不通的--仅仅因为所有的名字都以Q.4开头。有人能帮我吗?
更新
我希望将其传递给接受输入的函数,如下所示:
multichoice<-function(data, question.prefix){
index<-grep(question.prefix, names(data)) # identifies the index for the available options in Q.12
cases<-length(index) # The number of possible options / columns
# Identify the range of possible answers for each question
# Step 1. Search for the min in each col and across each col choose the min
# step 2. Search for the max in each col and across each col choose the max
mn<-min(data[,index[1:cases]], na.rm=T)
mx<-max(data[,index[1:cases]], na.rm=T)
d = colSums(data[, index] != 0, na.rm = TRUE) # The number of elements across column vector, that are different from zero.
vec<-matrix(,nrow=length(mn:mx),ncol=cases)
for(j in 1:cases){
for(i in mn:mx){
vec[i,j]=sum(data[, index[j]] == i, na.rm = TRUE)/d[j] # This stores the relative responses for option j for the answer that is i
}
}
vec1<-as.data.frame(vec)
names(vec1)<-names(data[index])
vec1<-t(vec1)
return(vec1)
}我使用我的功能的方式是
q4 <-multichoice(df2,"^Q.4")在"^Q.4“中,我打算标识Q.4的列,而df2是我的数据。
发布于 2016-05-26 11:39:47
下面是一个使用grep的方法:返回索引
grep("^Q\\.4[^0-9]", d)栏名:
grep("^Q\\.4[^0-9]", d, value=T)这是因为^0-9表示任何不是数字的字符,所以我们从字面上匹配Q.4,然后将字符串与任何非数字匹配。
我相信在mn语句中,您想要的是
mn <- min(sapply(data[,index], min, na.rm=T), na.rm=T)sapply通过按选定的grep索引选择的列移动,并在min中找到最小值。然后,将min应用于所有列。
发布于 2016-05-26 11:27:47
我们可以用stringr,
library(stringr)
str_extract(d, 'Q.[0-9]+') == 'Q.4'
#[1] FALSE FALSE FALSE FALSE FALSE FALSE TRUE TRUE
#or
d[str_extract(d, 'Q.[0-9]+') == 'Q.4']
#[1] "Q.4a-some Text" "Q.4b-some Text"如果格式总是相同的(即Q.0-9.)然后我们可以使用gsub
gsub('\\D', '', d) == 4
#[1] FALSE FALSE FALSE FALSE FALSE FALSE TRUE TRUEhttps://stackoverflow.com/questions/37458992
复制相似问题