sun*_*ad1 6 r string-length dataframe
我希望计算该列中每个字符串的字符数name。我的数据框sample如下所示:
date name expenditure type
23MAR2013 KOSH ENTRP 4000 COMPANY
23MAR2013 JOHN DOE 800 INDIVIDUAL
24MAR2013 S KHAN 300 INDIVIDUAL
24MAR2013 JASINT PVT LTD 8000 COMPANY
25MAR2013 KOSH ENTRPRISE 2000 COMPANY
25MAR2013 JOHN S DOE 220 INDIVIDUAL
25MAR2013 S KHAN 300 INDIVIDUAL
26MAR2013 S KHAN 300 INDIVIDUAL
Run Code Online (Sandbox Code Playgroud)
为什么会给nchar我一个随机数列表?str_length()从stringr包中也是如此
Length <- aggregate(nchar(sample$name), by=list(sample$name), FUN=nchar)
Run Code Online (Sandbox Code Playgroud)
输出
Group.1 x
1 JASINT PVT LTD 2
2 JOHN DOE 1
3 JOHN S DOE 2
4 KOSH ENTRP 2
5 KOSH ENTRPRISE 2
6 S KHAN 1, 1, 1
Run Code Online (Sandbox Code Playgroud)
期望的输出:
Group.1 x
1 JASINT PVT LTD 14
2 JOHN DOE 8
3 JOHN S DOE 10
4 KOSH ENTRP 10
5 KOSH ENTRPRISE 14
6 S KHAN 6
Run Code Online (Sandbox Code Playgroud)
上表的 csv:
"Date","name","expenditure","type"
"23MAR2013","KOSH ENTRP",4000,"COMPANY"
"23MAR2013 ","JOHN DOE",800,"INDIVIDUAL"
"24MAR2013","S KHAN",300,"INDIVIDUAL"
"24MAR2013","JASINT PVT LTD",8000,"COMPANY"
"25MAR2013","KOSH ENTRPRISE",2000,"COMPANY"
"25MAR2013","JOHN S DOE",220,"INDIVIDUAL"
"25MAR2013","S KHAN",300,"INDIVIDUAL"
"26MAR2013","S KHAN",300,"INDIVIDUAL"
Run Code Online (Sandbox Code Playgroud)
您还可以apply nchar到数据框并从相应的列中获取结果:
data.frame(names=temp$name,chr=apply(temp,2,nchar)[,2])
names chr
1 KOSH ENTRP 10
2 JOHN DOE 8
3 S KHAN 6
4 JASINT PVT LTD 14
5 KOSH ENTRPRISE 14
6 JOHN S DOE 10
7 S KHAN 6
8 S KHAN 6
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
47096 次 |
| 最近记录: |