{r setup, include=FALSE} knitr::opts_chunk$set(echo = TRUE)
This is an R Markdown document. Markdown is a simple formatting syntax for authoring HTML, PDF, and MS Word documents. For more details on using R Markdown see http://rmarkdown.rstudio.com.
When you click the Knit button a document will be generated that includes both content as well as the output of any embedded R code chunks within the document. You can embed an R code chunk like this:
library(dplyr)
word <- c(
"기차", "배", "버스", "비행기", "소방차/불자동차", "썰매", "오토바이", "유모차", "자전거", "차/자동차",
"택시", "트럭", "헬리콥터", "공", "로봇", "연필", "책", "총", "풍선", "개", "개구리", "개미", "거북이",
"거위", "고양이", "곰", "공룡", "기린", "나비", "다람쥐", "닭", "당나귀", "동물", "돼지", "말", "물고기",
"뱀", "벌", "병아리", "부엉이", "비둘기", "사슴", "사자", "새", "소", "송아지", "악어", "양", "여우",
"염소", "오리", "원숭이", "쥐", "참새", "코끼리", "토끼", "펭귄", "하마", "호랑이", "가방", "구두",
"기저귀", "단추", "모자", "목걸이", "바지", "목도리", "신/신발", "양말", "옷/꼬까", "운동화", "잠바",
"잠옷", "장갑", "주머니", "치마", "코트/외투", "팬티", "허리띠", "계단", "냉장고", "목욕탕", "문", "방",
"베개", "부엌", "서랍", "세탁기", "소파", "옷장", "의자", "이불", "전자레인지", "지하철", "창문", "침대",
"텔레비전", "피아노", "화장실", "감", "감자", "계란/달걀", "고구마", "귤", "당근", "도너츠", "떡",
"라면", "메론", "밤", "배추", "복숭아", "사과", "수박", "옥수수", "케이크", "콩", "토마토", "핫도그",
"햄버거", "호떡", "호박", "고추", "귀", "눈", "다리", "등", "똥꼬", "머리", "목", "몸", "무릎", "발",
"발목", "발톱", "배", "배꼽", "뺨", "손", "손가락", "어깨", "얼굴", "엉덩이", "이/이빨", "입", "입술",
"코", "턱", "팔", "허리", "혀", "가위", "그릇", "망치", "못", "병", "비누", "빗", "빗자루", "상자",
"수건", "숟가락", "시계", "쓰레기통/휴지통", "안경", "열쇠", "옷걸이", "우산", "쟁반", "전화", "접시",
"젓가락", "지갑", "청소기", "칫솔", "카메라", "칼", "컵", "포크", "휴지", "그네", "깃발", "꽃", "나무",
"달", "미끄럼틀", "사다리", "시소"
)
shape <- read.csv(file.choose(),fileEncoding="utf-8") #interactively choose the csv file
shape.ori <- shape
colnames(shape) # 칼럼 19에서 49까지가 CDI 질문
shape <- shape[1:dim(shape)[1], c(9, 26:56)]
# write.csv(shape, file="shape.csv", row.names=F)
Figure out what columns contain words. We can see that column2 through column32 contains responses.
colnames(shape) # 25 돕는말까지가 어휘 응답
Generate a column that contains all words in the responses, i.e., child’s lexicon. Let’s try with one row.
# shape$lexicon[1] <- paste(c(shape[1, 2:25]), collapse = ", ")
This works for one row. Now apply the concatenation operation to all rows in the dataframe.
shape$lexicon <- apply(shape[, 2:25], 1, function(row) paste(row, collapse = ", "))
#shape$lexicon <- do.call(paste, c(shape[2:25], sep = ", "))
In R, the apply function is used to apply a function over the margins of an array or matrix. Here are the arguments of the apply function:
X (Required): The array or matrix over which the function will be applied. MARGIN (Required): An integer vector indicating which margins should be retained. It can be 1 for applying the function over rows, 2 for applying the function over columns, or c(1, 2) for applying the function over both rows and columns. FUN (Required): The function to be applied. It can be a built-in function, a user-defined function, or an anonymous function.
shape$lexicon now contains the concatenated strings for
each row from columns 2 to 32
Now, generate a column called subset that contains only
the shape words in the lexicon
shape$subset <- sapply(strsplit(shape$lexicon, ", "), function(x) {
common_words <- intersect(x, word)
if (length(common_words) > 0) {
paste(common_words, collapse = ", ")
} else {
""
}
})
In this code:
strsplit(shape$lexicon, ", ") splits the words in
shape\(lexicon into individual elements based
on the comma and space separator. `intersect(x, word)` finds the common
elements between the split words and the word vector. The `sapply`
function applies the function to each element of the split words in
shape\)lexicon. paste(common_words, collapse = ", ")
concatenates the common elements back into a comma-separated string. If
there are no common words, “” is assigned to the subset column.
This will create a subset column in your shape dataframe containing the words that are members of the word vector for each row.
Let’s now generate a column called prop that shows the
proportion of shape words in the child’s lexicon.
# Apply strsplit function to split words and calculate proportion
shape$prop <- sapply(1:nrow(shape), function(i) {
lexicon_words <- unlist(strsplit(shape$lexicon[i], ", "))
non_empty_lexicon_words <- lexicon_words[lexicon_words != ""]
subset_words <- unlist(strsplit(shape$subset[i], ", "))
# Calculate the proportion of words in subset relative to lexicon
prop <- length(subset_words) / length(non_empty_lexicon_words)
# Return the proportion
return(prop)
})
Now save the results into a csv file.
write.csv(shape, file = "shape_result.csv", fileEncoding = "UTF-8", row.names = FALSE)