如何在 R DataFrame 中按列查找最大字符串长度?
在本文中,我们将了解如何在 R 编程语言中按列查找最大字符串长度。
要在给定数据帧中按列查找最大字符串长度,首先调用 nchar()函数以获取数据帧特定列中存在的所有字符串的长度,然后必须调用 max()函数以获取nchar()函数生成的字符串长度的最大值。 nchar() 和 max()函数是 R 编程语言的基本函数,因此无需导入任何包。
nchar()函数接受一个字符向量作为参数,并返回一个向量,其元素包含 x 对应元素的大小
Syntax:
nchar(x, type = “chars”, allowNA = FALSE, keepNA = NA)
Parameter:
- x: character vector or a vector to be coerced to a character vector. Giving a factor is an error.
- type:character string: partial matching to one of c(“bytes”, “chars”, “width”). See ‘Details’.
- allowNA: logical, should NA be returned for invalid multibyte strings or “bytes”-encoded strings (rather than throwing an error)?
- keepNA:logical: should NA be returned where ever x is NA?
max()函数在提供的数据中找到最大值。
Syntax:
MAX(vector, rank = 1, value = FALSE, rank.adjust = TRUE, forceChoice = FALSE)
Parameter:
- vector: Vector in which maximum/minimum element needs to be identified
- rank:value(s) or rank(s) of maximum values.
- value: Should value or rank be returned?
- rank.adjust: If the maximum value of a range of ranks exceeds vector length, should this be adjusted?
- forceChoice: In the case of ties, should all results be returned or only one?
示例 1:
R
gfg_data <- data.frame(x = c("geeks", "for", "geeks"),
y = c("I", "Love", "Coding"),
z=c("R", "programming ", "language"))
max(nchar(gfg_data$y))
R
gfg_data <- data.frame(x = c("geeks", "for", "geeks"),
y = c("I", "Love", "Coding"),
z=c("R", "programming ", "language"))
max(nchar(gfg_data$z))
输出:
[1] 6
示例 2:
电阻
gfg_data <- data.frame(x = c("geeks", "for", "geeks"),
y = c("I", "Love", "Coding"),
z=c("R", "programming ", "language"))
max(nchar(gfg_data$z))
输出:
[1] 12