gpt4 book ai didi

r - 在R中的数据帧的列中查找每个字符串的长度

转载 作者:行者123 更新时间:2023-12-04 10:50:44 24 4
gpt4 key购买 nike

我想计算 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

为什么会这样 nchar给我一个随机数列表? str_length()也是如此来自 stringr包裹
Length <- aggregate(nchar(sample$name), by=list(sample$name), FUN=nchar)

输出
         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

期望输出:
     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

上表的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"

最佳答案

您也可以 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

关于r - 在R中的数据帧的列中查找每个字符串的长度,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/28958101/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com