【问题标题】:Error in nchar(Tony.raw$neighborhood_overview) : 'nchar()' requires a character vectornchar(Tony.raw$neighborhood_overview) 中的错误:“nchar()”需要字符向量
【发布时间】:2019-12-16 10:59:54
【问题描述】:

链接到 .CSV 数据 https://drive.google.com/open?id=1mGsy52nZtRNpAFEWiWaJHB2nsm2hnvsU

nchar 中的错误(Tony.raw$neighborhood_overview): 'nchar()' 需要一个字符向量

我不知道为什么 nchar 无法读取到neighbor_overview 列

我有一项任务,其中提供了 CSV 文件,以获取问卷调查中有关丹佛社区社会统计数据的数据。我需要计算某些数据列的字符长度,然后将它们绘制成图表以表示数据中可用的某些观点。

我要在不同的数据列上尝试相同的代码,看看我得到了什么。

#Load up the .CSV data and explore in RStudio
Tony.raw <- read.csv("denver_listings.csv", stringsAsFactors = FALSE)
View(Tony.raw)

# Clean up the data frame and view our handiwork.
Tony.raw <- Tony.raw[, c("description", "neighborhood_overview")]
View(Tony.raw)

# Check data to see if there are missing values.
length(which(!complete.cases(Tony.raw)))

#Convert our class label into a factor.
Tony.raw$neighborhood_overview <- 
as.factor(which(complete.cases(Tony.raw$neighborhood_overview)))

# The first step , as always, is to expore the data.
#First, let's take a look at distribution of the class labels (i.e., ham 
vs. spam),
prop.table(table(Tony.raw$neighborhood_overview))

#Next up , let's get a feel for the distribution of text lengths of the 
SMS
# messages by adding a new dearture for the length of each message.
Tony.raw$TextLength <- nchar(Tony.raw$neighborhood_overview)
summary(Tony.raw$TextLength)

#Visualize distribution with ggplot2, adding segmentation for ham/spam
library(ggplot2)

ggplot(Tony.raw, aes(x=TextLength, fill = neighborhood_overview)) +
  theme_bw() +
  geom_histogram(binwidth = 5) +
  labs(y = "Text Count", x = "Length of Text",
       title = "Distribution of Text Lengths with class Labels")

将 Tony.raw$TextLength 设置为 Tony.raw$neighborhood_overview 的 nchar,我应该能够计算字符数,然后用 ggplot2 将其绘制到图表中。但它说 nchar 需要一个字符向量。是因为描述数据不是字符还是列标签不是字符?我不知道。

【问题讨论】:

  • 要在此站点上获得帮助,您应该使用dput(Tony.raw) 分享您的一小部分数据。如果人们可以复制和粘贴而不是下载整个数据集,那么他们会更容易为您提供帮助。查看this link,了解有关在此处提问的提示

标签: r csv large-data nchar


【解决方案1】:

在代码的第四块中,您已将 Tony.raw$neighborhood_overview 转换为 factor。 你需要

nchar(labels(Tony.raw$neighborhood_overview)[Tony.raw$neighborhood_overview])

而不是nchar(Tony.raw$neighborhood_overview) 获取因子标签的nchar

当您编写 nchar(Tony.raw$neighborhood_overview) 时,它会在因子的 levels 上调用 nchar,这是从 1 到级别数的整数值并引发错误因为 nchar 获取数字而不是字符串。

【讨论】:

  • 我只有一个数字矩阵,我也有同样的问题。此外,按照包中的示例 (omega(Thursntone) 出现相同的错误消息
猜你喜欢
  • 2022-06-10
  • 2012-01-15
  • 2013-04-05
  • 1970-01-01
  • 2016-12-25
  • 2014-12-07
  • 2011-03-27
  • 2018-03-01
相关资源
最近更新 更多