<p>我使用了一个函数,该函数将访问每个column元素并检查元素是否为一个空格(您可以根据所拥有的内容更改该元素)。它在我看来像一个空格),如果是,则返回0,否则它用“\t”拆分字符串并计算生成的字符串。在</p>
<pre><code># example dataset
dt = data.frame(col1 = c("green\twhite3\t3blue5","green"),
col2 = c(" ", "green\twhite3"), stringsAsFactors = F)
dt
# col1 col2
# 1 green\twhite3\t3blue5
# 2 green green\twhite3
ff = function(x)
{
res = vector() # create an empty vector to store counts for each element
for (i in 1:length(x)){ # iterate through each element
res[i] = ifelse(x[i]==" ", 0, length(unlist(strsplit(x[i],"\t")))) # if the element is space return 0, else split string by \t and count new strings
}
return(res) # return the stored values
}
data.frame(sapply(dt, function(x) ff(x))) # apply the function to all columns and save it as a data.frame
# col1 col2
# 1 3 0
# 2 1 2
</code></pre>