如何在R中将表转换为数据框?
在本文中,我们将讨论如何在 R 编程语言中将给定的表转换为数据帧。
使用的功能
- as.data.frame.matrix()将表作为其参数并将数据帧返回给用户。
Syntax: as.data.frame.matrix(x)
Parameter:
- x: name of the table which is to be converted into dataframe
Returns: It will return the dataframe which is converted from the given data.
- table()函数用于交叉分类因子,以构建 R 语言中提供的数据的每个因子级别组合的计数列联表。
Syntax: table(…,exclude = if (useNA == “no”) c(NA, NaN),useNA = c(“no”, “ifany”, “always”),dnn = list.names(…), deparse.level = 1)
Returns:
This function will be returning the frequency table of the provided data back to the user.
因此,我们将首先使用 table()函数从数据帧创建一个列联表,然后将该表转换为数据帧。
下面给出了一些实现。
示例 1:
R
data_gfg=data.frame(x=c(1,3,5,3,4),
y=c(1,5,1,4,5))
table_gfg=table(data_gfg$x,data_gfg$y)
print("table in use: ")
table_gfg
new_data_gfg=as.data.frame.matrix(table_gfg)
print("converted to dataframe: ")
new_data_gfg
R
data_gfg=data.frame(x=c("a","b","c","d","e"),
y=c("1","2","3","4","5"))
table_gfg=table(data_gfg$x,data_gfg$y)
print("table in use: ")
table_gfg
new_data_gfg=as.data.frame.matrix(table_gfg)
print("dataframe after conversion :")
new_data_gfg
输出:
示例 2:
电阻
data_gfg=data.frame(x=c("a","b","c","d","e"),
y=c("1","2","3","4","5"))
table_gfg=table(data_gfg$x,data_gfg$y)
print("table in use: ")
table_gfg
new_data_gfg=as.data.frame.matrix(table_gfg)
print("dataframe after conversion :")
new_data_gfg
输出: