简体   繁体   English

在 R 如何从从标准输入读取值创建数据帧

[英]In R How to create data frame from Read values from stdin

How to read the below stdin values and create a data frame in R.如何读取以下标准输入值并在 R 中创建数据框。 Here stdin values are dynamic这里标准输入值是动态的

PrimeSuperMarket
4
Choclate
Jam
Milk
Rice

Line 1 denotes ShopName第 1 行表示 ShopName

Line 2 denotes NumberOfItems Planning to purchase第 2 行表示 NumberOfItems 计划购买

Line 3 to 7 : Item Type第 3 到 7 行:项目类型

Line No 3 to n is dynamic that depends upon line no 2 value.第 3 行到第 n 行是动态的,取决于第 2 行的值。 If value is passed as 5 in line 2. Line 3 to Line 8 will be there, So totally 5 values will be entered.如果在第 2 行中将 value 作为 5 传递。第 3 到第 8 行将在那里,因此总共将输入 5 个值。

My Expected output is我预期的 output 是

在此处输入图像描述

If your input file is called input.txt you can read it with readLines and create a dataframe like so -如果您的输入文件名为input.txt ,您可以使用readLines读取它并像这样创建 dataframe -

val <- readLines('input.txt')
shopName <- val[1]
Item <- val[3:(3 + as.numeric(val[2]) - 1)]
# Or you can read everything removing 1st 2 values
#Item <- val[-c(1:2)]
data.frame(shopName, Item)


#          shopName     Item
#1 PrimeSuperMarket Choclate
#2 PrimeSuperMarket      Jam
#3 PrimeSuperMarket     Milk
#4 PrimeSuperMarket     Rice

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM